Sharing my Java simple and easy to understand solution


  • 1
    V
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        
        if(head == null || head.next == null) return head;
    
        ListNode cur=head;
        head=head.next;    //setting head to second element as this will be the new head
        ListNode prev=null;
        while( cur != null ){
            if(prev != null){
                if(cur.next == null){
                    prev.next=cur;      // for odd length example: 1->2->3
                }
                else{
                    prev.next=cur.next;   // for even length example: 1->2->3->4 
                }
            }
            ListNode nextNext=null;
            if(cur.next != null){        // for even length
                nextNext=cur.next.next;
                cur.next.next=cur;
            }
            cur.next=null;
            prev=cur;
            cur=nextNext;
        }
        return head;
    }
    

    }


Log in to reply
 

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