Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 738 Bytes

Reverse Linked List.md

File metadata and controls

42 lines (33 loc) · 738 Bytes

Notes

Iterative solution using 3 pointers.

Provided code

class ListNode {
    ListNode next;
}

Solution

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = null;
        ListNode curr = head;
        ListNode next = null;
        while (curr != null) {
            next = curr.next;
            curr.next = prev; // changes arrow direction
            prev = curr;
            curr = next;
        }
        return prev;
    }
}

Time/Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Links