Simple java solution 5ms


  • 0
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null){
                return null;
            }
            if(head.next==null){
                return head;
            }
            ListNode temp=head.next;
            ListNode hnode = head;
            ListNode runner=null;
            while(hnode.next!=null){
                runner=hnode.next;
                hnode.next=runner.next;
                runner.next=hnode;
                if(hnode.next==null){
                    break;
                }
                if(hnode.next.next==null){
                    break;
                }
                if(hnode.next!=null && hnode.next.next!=null){
                    runner=hnode.next;
                    hnode.next=runner.next;
                    hnode=runner;
                }
            }
            return temp;
        }
    }

Log in to reply
 

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