PracticeNeetCode ↗LeetCode ↗
Given the head of a singly linked list, reverse the list in place and return the new head.
next to its predecessor instead of its successor.prev pointer starting at None — that becomes the new head once the loop ends.curr.next, or the rest of the list is lost.prev = None, curr = head.curr is not None: save next_node = curr.next.curr.next = prev, then advance prev = curr, curr = next_node.curr is None, prev is the new head — return it.Time: O(n) — Space: O(1)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode | None) -> ListNode | None:
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prevHow the solution above works, piece by piece.
prev = None: the reversed part starts empty (the old head will end up pointing to None).next_node = curr.next: save the rest of the list before changing any pointer, or it would be lost.curr.next = prev: flip this node to point backwards.prev = curr, curr = next_node: step both pointers forward.curr is None, prev is the old tail, which is the new head. O(n) time, O(1) space.Running it on head = [1, 2, 3, 4, 5]:
prev. Right chain: the part not reached yet, headed by curr. Each loop moves one node from the right chain to the front of the left chain.