Java solution


  • 0
    H
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next==null) return head;
            ListNode[] pair= new ListNode[2];
            ListNode p = head;
            ListNode last = null;
            while(p != null){
                if(pair[0]==null){
                    pair[0]=p;
                }else if (pair[1] == null){
                    pair[1]=p;
                }
                p= p.next;
                if(pair[0] != null && pair[1] != null){
                    //swap at here
                    if(last != null){
                        last.next= pair[1];
                    }else{
                        head = pair[1];
                    }
                    pair[1].next= pair[0];
                    pair[0].next= null;
                    last = pair[0];
                    pair[0]=null;
                    pair[1]=null;
                }
            }
            if(pair[0] != null){
                last.next=pair[0];
                pair[0].next=null;
            }
            return head;
        }
    }
    

Log in to reply
 

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