Singly Linked List
Idea Like You Are 10
A singly linked list is like a chain of train cars.
Each car has:
- some data
- a link to the next car
The last car points to NULL, which means "no more cars".
Representation In Memory
Each node stores:
Example:
Important:
- nodes may be stored in different memory places
- the links connect them logically
So memory may look like this:
Even though the nodes are not next to each other in memory, the list still works.
Basic Operations
1. Traversing
Move from node to node until NULL.
Time: O(n)
Why: in the worst case you visit every node once.
2. Searching
Check nodes one by one until the value is found or the list ends.
Time:
- Best:
O(1) - Worst:
O(n)
Why:
- best case: key is at the head
- worst case: key is at the end or not present
3. Insertion At Beginning
Create a new node and make it the new head.
Time: O(1)
Why: only pointer updates are needed.
4. Insertion At End
Walk to the last node, then attach the new node.
Time: O(n)
Why: you may need to walk through the whole list.
5. Insertion After A Given Node
Time: O(1) if the node is already known.
6. Deletion From Beginning
Time: O(1)
7. Deletion From End
Time: O(n)
Why: you must reach the second last node.
8. Deletion Of A Given Key
Time:
- Best:
O(1) - Worst:
O(n)
Complexity Summary
| Operation | Time |
|---|---|
| Traverse | O(n) |
| Search | O(n) |
| Insert at front | O(1) |
| Insert at end | O(n) |
| Insert after known node | O(1) |
| Delete from front | O(1) |
| Delete from end | O(n) |
| Delete given key | O(n) |
Space Complexity
Each node stores:
- data
- one pointer
Total list space: O(n)
Extra working space for normal operations: O(1)
Advantages
- Easy insert/delete at front
- Dynamic size
- No need for contiguous memory
Disadvantages
- No direct access like arrays
- Extra memory for pointer
- One-way movement only