Java Code with Explanation

  • 0
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==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); = head;
        head = dummy;
        //2. Check if the next two nodes are not 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 =;
            ListNode second =;
            ListNode temp =;
   = first;
   = temp;
   = second;
            head =;


Log in to reply

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