Skip to content

206. Reverse Linked ListΒΆ

Problem Link

To solve this in a single pass, we can use two pointers, prev and curr. The prev pointer represents the previous node and will become the next pointer for the current node curr. reverse_linked_list.png While reversing the link for curr, we must first store its original next node in a temporary variable. This prevents losing the remaining part of the list and allows us to move forward to the next node.

Runtime Complexity

Time: \(O(n)\)

Space: \(O(1)\)

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        curr = head
        while curr:
            nxt = curr.next
            curr.next = prev
            prev = curr
            curr = nxt
        return prev
func reverseList(head *ListNode) *ListNode {
    var prev, next *ListNode
    curr := head
    for curr != nil {
        next = curr.Next
        curr.Next = prev
        prev = curr
        curr = next
    }
    return prev
}