Linked List
What is a Linked List?
A linked list is a linear data structure where elements are stored in nodes, and each node points to the next node in the sequence. Unlike arrays, linked list elements are not stored in contiguous memory locations.
Basic Structure
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
Types of Linked Lists
- Singly Linked List: Each node points to the next node
- Doubly Linked List: Each node has pointers to both next and previous nodes
- Circular Linked List: Last node points back to the first node
Time Complexity
Operation | Time Complexity |
---|---|
Access | O(n) |
Search | O(n) |
Insertion | O(1)* |
Deletion | O(1)* |
* When position is known, otherwise O(n) to find position
Space Complexity
- O(n) where n is the number of nodes
Advantages
- Dynamic size
- Efficient insertion/deletion at beginning
- No memory wastage
- Implementation of other data structures (stacks, queues)
Disadvantages
- No random access
- Extra memory for pointers
- Not cache friendly
- No reverse traversal (in singly linked list)
Real-world Applications
- Implementation of file systems
- Previous/Next page in web browsers
- Music playlist management
- Undo/Redo operations in software
- Symbol table management in compiler design
Common Interview Problems
- Reverse a linked list
- Detect cycle in a linked list
- Find middle element
- Merge two sorted lists
- Remove nth node from end
Common Techniques
- Two-pointer technique
- Floyd's cycle finding algorithm
- Dummy head node
- Runner technique
- Recursive solutions