Linked List
A linked list is a fundamental data structure that represents a sequence of elements. Each element, known as a node, contains:
- Data (Value): The information stored in the node.
- Reference (Pointer): A link to the next node in the sequence.
The first node is called the head, and the last node is the tail, which points to None, indicating the end of the list.
Node Structure in Python
Here's an example of a simple node class for a singly linked list:
class ListNode:
"""Node class for a singly linked list."""
def __init__(self, val: int):
self.val: int = val # Data stored in the node
self.next: 'ListNode' = None # Reference to the next node
Creating a Linked List
To build a linked list, instantiate nodes and link them using their next references:
# Create nodes with values
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# Link nodes: 1 -> 3 -> 2 -> 5 -> 4
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
# Set the head of the list
head = n0
Common Operations on Linked Lists
Time Complexity Comparison
| Operation | Array | Singly Linked List | Doubly Linked List | Circular Linked List |
|---|---|---|---|---|
| Access by Index | O (1) | O (n) | O (n) | O (n) |
| Insertion at Head | O (n) | O (1) | O (1) | O (1) |
| Deletion at Head | O (n) | O (1) | O (1) | O (1) |
| Insertion at Tail | O (1)* | O (n)** | O (1) | O (1) |
| Deletion at Tail | O (1)* | O (n) | O (1) | O (1) |
| Search by Value | O (n) | O (n) | O (n) | O (n) |
* If the array has unused capacity at the end.
** O (1) if a tail reference is maintained.
Inserting a Node
To insert a node P after a node n0:
def insert(n0: ListNode, P: ListNode):
"""Insert node P after node n0 in the linked list."""
P.next = n0.next
n0.next = P