Java implementation for Time O(N), Space O(1)


  • 0
    I

    Have to use a previous pointer to keep track to the next pair, the solution is shown below:

    public ListNode swapPairs(ListNode head) {

        if(head==null || head.next == null){
            return head;
        }
        
        ListNode c = head;
        head = c.next;
        ListNode p = null;
        
        while(c!=null && c.next!=null){
            
            ListNode cn = c.next;
            ListNode cnn = c.next.next;
            cn.next = c;
            c.next = null;
            if(p!=null){
                p.next = cn;
            }
            p = c;
            c = cnn;
        }
        
        if(c!=null && p!=null){
            p.next = c;
            c.next = null;
        }
        return head;
    }

Log in to reply
 

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