Simple Iterative solution


  • 1
    S

    Swap all pairs one by one..

    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head ==null || head.next==null) return head;
            
            ListNode newHead = head.next; 
            
            ListNode current = head;
            ListNode prev = null;
            ListNode temp = null;
            while(current !=null && current.next!=null){
                prev = current.next;
               // connect 2*ith node to new 2*i+1th node
                if(temp !=null){
                    temp.next = prev;
                } 
                //swap ith  & i+1th node
                current.next = prev.next;
                prev.next = current;
                temp = current;
                current = current.next;
            }
            
            return newHead;
        }
    }
    

Log in to reply
 

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