DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #206. Reverse Linked List

Time Complexity: O(n)

Space Complexity: O(1)

class Solution {
    public ListNode reverseList(ListNode head) {

        // these variables are references, not copies of the node itself
        // so we are not using them as copies of the nodes, but as references (pointers)
        ListNode previous = null;
        ListNode current = head;
        ListNode next = null;

        while (current != null) {

            next = current.next; // save next
            current.next = previous; // reverse

            // advance previous & current
            previous = current; // previous points to the old current
            current = next; // current points to the old next
        }

        return previous; // new head at the end

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)