What is a Linked List?
A linked list is a data structure where elements are connected via pointers, allowing dynamic size and efficient insertion/deletion.
A linked list is a data structure where each element (node) contains data and a reference to the next node. Think of it like a treasure hunt: each clue points to the next location, and you follow the chain to find all the treasures.
Structure:
- Node: Contains data and a pointer to the next node
- Head: The first node in the list
- Tail: The last node (points to null/nothing)
Types:
- Singly linked: Each node points to the next
- Doubly linked: Each node points to both next and previous
- Circular: The last node points back to the first
Advantages:
- Dynamic size: Grows and shrinks as needed
- Easy insertion/deletion: Just update pointers
- No wasted space: Only uses memory for what you store
Disadvantages:
- No random access: Can't jump to index 5 directly
- Extra memory: Need to store pointers
- Slower traversal: Must follow the chain
FAQ
When should I use a linked list vs an array?
Use arrays when you need random access. Use linked lists when you frequently insert/delete from the middle and don't need random access.
Are linked lists faster than arrays?
It depends. Arrays are faster for access, linked lists are faster for insertion/deletion in the middle (no shifting needed).