A linked list is a linear data structure where elements, called nodes, are connected using pointers. Each node in a linked list contains two parts:
Value: Holds the value/data for the Node.
Next (pointer): Holds a reference (pointer) to the next Node.
The head is the first node in the linked list. It is the starting point for traversal through the list.
The tail is the last node in the linked list.
1. Append (O(1))
- Operation: Add an item to the end of the list.
- Reason: If a reference to the tail node is maintained, appending is constant time because you only update the
next
pointer of the tail.
2. Remove Last (O(n))
- Operation: Remove the last item from the list.
- Reason: In a singly linked list, you need to traverse the entire list to find the second-to-last node to update its
next
pointer tonull
. This traversal takes linear time.
3. Prepend (O(1))
- Operation: Add an item to the beginning of the list.
- Reason: You only need to update the
head
pointer to point to the new node, which takes constant time.
4. Remove First (O(1))
- Operation: Remove the first item from the list.
- Reason: You simply update the
head
pointer to point to the next node, which is a constant-time operation.
5. Insert (O(n))
- Operation: Insert an item at a specific position in the list.
- Reason: You need to traverse the list to find the insertion point, which takes linear time.
6. Remove (O(n))
- Operation: Remove an item at a specific position in the list.
- Reason: You need to traverse the list to find the node just before the one being removed, which takes linear time.
7. Lookup by Index (O(n))
- Operation: Access an item at a specific index.
- Reason: Unlike arrays, linked lists do not have direct indexing. You must traverse the list from the beginning to locate the node at the specified index.
8. Lookup by Value (O(n))
- Operation: Find an item by its value.
- Reason: You must traverse the entire list to compare each node's value, which takes linear time in the worst case.