Only need two new pointers O(1) space iterative JAVA code


  • 0
    Z

    O(n) time O(1) space
    Don't need dummy node, only need two more pointers to proceed and one more to record head.

        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null) return head;
            ListNode cur = head;  // Current start node
            head = head.next;
            while(cur != null && cur.next != null) {
                ListNode next = cur.next.next; // Next start node
                cur.next.next = cur;
                // Handle all cases of next batch
                cur.next = next != null ? (next.next != null ? next.next: next) : null;
                cur = next;
            }
            return head;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.