π Linked Lists
π What is a Linked List?
A linked list is a linear data structure where elements, called nodes, are not stored in contiguous memory locations. Instead, each node contains two parts: the data itself and a pointer (or reference) to the next node in the sequence.
Head: The entry point to the list, which is a pointer to the very first node.Tail: The last node in the list points toNone(ornull), indicating the end of the list.
β Basic Operations & Complexity
The performance of a linked list is very different from an array due to its structure.
- Access and Search: To find an element, you must start at the
headand traverse the list one node at a time.- Complexity:
O(n)
- Complexity:
- Insertion at the Beginning: A new node is created, its pointer is set to the current
head, and the listβsheadis updated to the new node.- Complexity:
O(1)
- Complexity:
- Insertion at the End: Requires traversing the entire list to find the last node, then updating its pointer.
- Complexity:
O(n)(orO(1)if you maintain a separate pointer to thetailnode).
- Complexity:
- Deletion from the Beginning: The
headpointer is simply moved to the second node.- Complexity:
O(1)
- Complexity:
- Deletion from the Middle/End: You must traverse the list to find the node before the one you want to delete to update its pointer.
- Complexity:
O(n)
- Complexity:
βοΈ Types of Linked Lists
- Singly Linked List: The standard version where each node has a pointer only to the next node. Traversal is one-way.
- Doubly Linked List: Each node has two pointers: one to the next node and one to the previous node. This allows for forward and backward traversal but uses more memory.
- Circular Linked List: The last nodeβs pointer points back to the head of the list instead of
None, forming a circle.
π Advantages
- Dynamic Size: Can grow and shrink easily without reallocating an entire block of memory.
- Efficient Insertions/Deletions: Very fast (
O(1)) to add or remove elements at the beginning of the list.
π Disadvantages
- No Random Access: You cannot access an element by its index in constant time. Accessing any element requires
O(n)traversal. - Extra Memory: Each node requires extra memory to store its pointer(s).
β οΈ Important Note: The primary trade-off between a linked list and an array is access vs. insertion/deletion. Use an array for fast
O(1)access. Use a linked list when you need efficientO(1)insertions and deletions at the beginning of a sequence.
Last updated on