Linked List Deletion
Visualization
Watch how elements are removed from a linked list:
Types of Deletion
1. Delete from Head
- Time Complexity: O(1)
- Most efficient deletion operation
public void deleteHead() {
if (head != null) {
head = head.next;
}
}
2. Delete from Tail
- Time Complexity: O(n)
- Requires traversal to second-last node
public void deleteTail() {
if (head == null || head.next == null) {
head = null;
return;
}
ListNode current = head;
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
3. Delete by Value
- Time Complexity: O(n)
- Requires traversal to find value
public void deleteValue(int val) {
if (head == null) return;
if (head.val == val) {
head = head.next;
return;
}
ListNode current = head;
while (current.next != null && current.next.val != val) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
}
}
Common Deletion Patterns
- Using dummy head node
- Two-pointer technique
- Handle edge cases (empty list, single node)
- Recursive deletion