# [LeetCode 24] Swap Nodes in Pairs

### Question

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.

### Stats

 Frequency 4 Diffficulty 2 Adjusted Difficulty 3 Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

### Solution

The easier solution is of course recursion. We only need to swap 2 nodes and then call the method recursively. Find code below.

However, there exists iterative solution, just slightly complex. Read here for more. Two pieces of iterative code are posted below.

### My code

Recursion

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
}
return temp;
}
}
``````

Iterative solution using while loop. ref

``````public ListNode swapPairs(ListNode head) {
while (cur != null && cur.next != null) {
pre.next = cur.next;
ListNode newCur = cur.next.next;
cur.next.next = cur;
cur.next = newCur;
pre = cur;
cur = newCur;
}
}
``````

Iterative solution using for loop. ref

``````public ListNode swapPairs(ListNode head) {
ListNode start = new ListNode(0);