Leetcode 206. Reverse Linked List
Reverse a singly linked list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL
What should be returned?
Return the head of the reversed linked list.
Can the list be empty?
Yes, the input list can be empty. In this case, return null
.
Is the input list guaranteed to be a singly linked list?
Yes.
prev
as null
, curr
as head, and next
as null
.prev
and curr
one step forward.null
or the next node is null
, return the current node.Here is the Java implementation using both iterative and recursive approaches.
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
In both approaches, the space complexity is O(1) for the iterative approach and O(n) for the recursive approach (due to the stack used for function calls).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?