# LeetCode – Swap Nodes in Pairs (Java)

For example, given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Java Solution 1

Use two template variable to track the previous and next node of each pair.

 public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head;   ListNode h = new ListNode(0); h.next = head; ListNode p = h;   while(p.next != null && p.next.next != null){ //use t1 to track first node ListNode t1 = p; p = p.next; t1.next = p.next;   //use t2 to track next node of the pair ListNode t2 = p.next.next; p.next.next = p; p.next = t2; }   return h.next; }

Java Solution 2

Each time I do the same problem I often get the different solutions. Here is another way of writing this solution.

 public ListNode swapPairs(ListNode head) { if(head==null || head.next==null) return head;   //a fake head ListNode h = new ListNode(0); h.next = head;   ListNode p1 = head; ListNode p2 = head.next;   ListNode pre = h; while(p1!=null && p2!=null){ pre.next = p2;   ListNode t = p2.next; p2.next = p1; pre = p1; p1.next = t;   p1 = p1.next;   if(t!=null) p2 = t.next; }   return h.next; }

### 12 thoughts on “LeetCode – Swap Nodes in Pairs (Java)”

1. Might be more a more clearer solution:

{

/* prev node before next pair */

/* Has next pair */
while (prev.next != null && prev.next.next != null)
{
/* Start of pair */
Node curr = prev.next;

/* Remember the next Pair */
Node nextPair = curr.next.next;

/* Swap */
prev.next = curr.next;
prev.next.next = curr;
curr.next = nextPair;

/* Iterate to next */
prev = curr;
}

}

2. 100% on leet code:

class Solution {

ListNode helper = new ListNode(0);

ListNode previous = helper;

while(current != null){
ListNode next = current.next;
if(next!=null){
current.next = next.next;
previous.next = next;
next.next = current;
previous = previous.next.next;
current = current.next;
}else{
current = current.next;
}
}

return helper.next;
}
}

3. No it doesn’t. Just tested both solution by hand and also on leetcode.
They are both correct.

4. in while loop : p.next != null is the same head == null in if condition ahead

5. Wow! Beautiful.

6. public static ListNode swapPairs(ListNode head) {
else{
// swap the two
}
}

7. class Solution {
public:

return temp;
}
};

8. hey dude, p.next.next = p; should change to t1.next.next=p;

}

ListNode parent=slow.next;

slow=slow.next.next;

while(slow!=null && slow.next!=null){

ListNode temp=slow.next;

slow.next=slow.next.next;

temp.next=slow;

parent.next=temp;

parent=parent.next.next;

slow=slow.next;

}

10. public ListNode swapPairs(ListNode head) {