Reverse Linked List
You're given the head of a singly linked list. Reverse it so the last node comes first and every link points the other way, then return the new head. Rearrange the existing nodes' next pointers rather than building a new list or copying values around. An empty list (a null head) is returned as an empty list.
Examples
head = [1,2,3,4,5] returns [5,4,3,2,1]
Every link flips direction: 5 now points to 4, 4 to 3, and so on, while 1 becomes the tail and points to null. The old tail 5 is the new head.
head = [] returns []
An empty list has no links to flip, so the result is also empty (a null head).
Constraints
- 0 <= n <= 5000
Hints
What three node references would you need to keep around to flip arrows one at a time?
Iterate with prev, curr, and a saved next pointer.
Initialize prev = null, curr = head. While curr is non-null: save next = curr.next, set curr.next = prev, then advance prev = curr and curr = next. Return prev.
Drill This: Your Approach First
Approach
Walk the list once with three references: prev (the reversed part so far, starting at null), curr (the node being processed) and a saved next. For each node, save curr.next, point curr.next back at prev, then step prev to curr and curr to the saved next. When curr falls off the end, prev is the old tail, which is the new head. O(n) time, O(1) extra space.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}class Solution:
def reverseList(self, head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev