LeetCode 206: Reverse Linked List
Problem Description
Explanation
To reverse a linked list, we can iterate through the list while reversing the pointers to point in the opposite direction. We need to keep track of the current node, the next node, and the previous node to perform the reversal.
-
Iterative Approach:
- Initialize three pointers:
prev
as null,curr
as the head of the list, andnext
as null. - Traverse the list while updating the pointers: set
next
tocurr.next
, pointcurr.next
toprev
, moveprev
tocurr
, and movecurr
tonext
. - Return
prev
as the new head of the reversed list.
- Initialize three pointers:
-
Recursive Approach:
- The base case is when the current node is null or the next node is null, return the current node.
- Recursively call the function on the next node, then reverse the pointers by setting
curr.next.next
tocurr
and setcurr.next
to null. - Return the new head of the reversed list.
- Time Complexity: O(n) where n is the number of nodes in the linked list.
- Space Complexity: O(1) for the iterative approach and O(n) for the recursive approach due to the stack space used in recursion.
Solutions
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
Related LeetCode Problems
Loading editor...