public ListNode reverse(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
// Keep temporary next node
ListNode next = current.next;
// Change link
current.next = previous;
// Move previous and current
previous = current;
current = next;
}
return previous;
}
Each node contains a pointer to the previous and the next node
Access: O(n)
Insert: O(1)
Delete: O(1)
Using the runner technique
while (l1 != null || l2 != null) {
}
Access: O(n)
Insert: O(1)
Delete: O(1)
Single or doubly linked list?
Insert: O(1)
Delete: O(1)
Insert: O(1)
Delete: O(1)
Data structure using a single, fixed-sized buffer as if it were connected end-to-end
Reverse the liked list (or a subpart only), implement the algo then reverse it again to the initial state