Easy-understanding java solution with constant space complexity


  • 0
    Y
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode temp1 = head;
        head = head.next;
        ListNode temp2 = head.next;
        head.next = temp1;
        temp1.next = temp2;
        ListNode i = head.next;
        boolean flag = true;
        while(i.next != null && i.next.next != null){
            if(flag){
                temp1 = i.next;
                i.next = i.next.next;
                temp2 = i.next.next;
                i = i.next;
                i.next = temp1;
                i.next.next = temp2;
                flag = false;
            }else{
                i = i.next;
                flag = true;
            }
            
        }
        return head;
    }

Log in to reply
 

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