Given the head of a singly linked list, our goal is to reverse the list, turning the elements backward so that the tail becomes the new head, and return the pointer to the new head node.
For example:
1 -> 2 -> 3 -> 4 -> 5 -> nullnull <- 1 <- 2 <- 3 <- 4 <- 5 (or 5 -> 4 -> 3 -> 2 -> 1 -> null)Click through our interactive animation to see how pointers get reassigned node-by-node. Notice how the pointers prev, curr, and nextTemp move in tandem.
To reverse a list iteratively, we traverse the list exactly once. As we visit each node, we change its next pointer to point to its predecessor instead of its successor.
Because a node's next pointer is overwritten, we must store the subsequent node in a temporary variable (nextTemp) before changing the link, so we do not lose track of the remaining list.
curr: The node we are currently visiting (starts at head).prev: The node preceding curr (starts at null, since the original head will become the new tail pointing to null).nextTemp: Holds reference to the next node (curr.next) before we sever the link.nextTemp = curr.nextcurr.next = prevprev = currcurr = nextTempHere is the clean implementation of Linked List Reversal:
class ListNode {
val: number;
next: ListNode | null;
constructor(val: number) {
this.val = val;
this.next = null;
}
}
function reverseList(head: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let curr: ListNode | null = head;
while (curr !== null) {
let nextTemp: ListNode | null = curr.next; // Save next node
curr.next = prev; // Reverse connection
prev = curr; // Move prev forward
curr = nextTemp; // Move curr forward
}
return prev; // prev will point to the new head
}class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next_temp = curr.next # Save next
curr.next = prev # Reverse link
prev = curr # Move prev
curr = next_temp # Move curr
return prevclass ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next; // Save next
curr.next = prev; // Reverse link
prev = curr; // Move prev
curr = nextTemp; // Move curr
}
return prev;
}
}Alternatively, we can reverse the list recursively. The recursive version traverses down to the end of the list first, and then reverses the pointer connections as the recursive calls pop off the call stack.
def reverseListRecursive(head: ListNode) -> ListNode:
# Base cases: empty list or single node
if not head or not head.next:
return head
# Reverse the rest of the list
new_head = reverseListRecursive(head.next)
# Put head at the end of the reversed list
head.next.next = head
head.next = None
return new_headStay sharp for coding assessments and final exams! Use our free academic tools, including the GPA to Percentage Calculator, to check your academic stats and keep your records in order.
Found this article helpful? Share it with others!
More articles you might find helpful
Learn the optimal O(n) time and O(1) space solution for LeetCode 234: Palindrome Linked List using the Two-Pointer technique.
Master LeetCode 203: Remove Linked List Elements. Learn how the Dummy Node technique effortlessly handles edge cases with our interactive visualizer and code guides.
Master the LeetCode 837 New 21 Game using dynamic programming and a sliding window approach with interactive visualizers.
Use our free AnaCGPA Calculator for instant and accurate grade calculation. Simple, fast, and no sign-up required.