Java Code with Explanation


  • 0
    M
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null) return head;
    
        //1. Problem requires constant space & in place. The head node will change during the swap, so we create dummy node, let head point to the prev node.
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
    
        //2. Check if the next two nodes are not null
        while(head.next!=null&&head.next.next!=null){
    
            //3. Swap. Store the list after the second node for swapping. Set first node to the next of second node. Set second node to the next of dummy node. Move dummy node to current position of first node.
            ListNode first = head.next;
            ListNode second = head.next.next;
            ListNode temp = second.next;
            second.next = first;
            first.next = temp;
            head.next = second;
            head = head.next.next;
    
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

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