Java constant space and linear time solution


  • 0
    G
    public ListNode swapPairs(ListNode head) {
        if(head == null) return head;
        ListNode curr = head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        while(curr != null){
            if(curr.next == null) break;
            ListNode temp = curr.next;
            curr.next = temp.next;
            temp.next = curr;
            prev.next = temp;
            prev = curr;
            curr = curr.next;
        }
        return dummy.next;
    }

Log in to reply
 

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