# Swap Nodes in Pairs

## Question

### Problem Statement

#### Example

Given 1->2->3->4, you should return the list as 2->1->4->3.

#### Challenge

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

## 题解1 - Iteration

1. 保存2.next
2. 2.next赋值为1
3. 1.next赋值为1中保存的2.next
4. 将前一个链表节点的 next 指向1
5. 更新前一个链表节点为1
6. 更新当前的链表节点为1中保存的2.next

### Java

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @return a ListNode
*/
ListNode dummy = new ListNode(0);
ListNode prev = dummy, curr = head;

while (curr != null && curr.next != null) {
ListNode after = curr.next;
ListNode nextCurr = after.next;
after.next = curr;
curr.next = nextCurr;
// link new node after prev
prev.next = after;
// update prev and curr
prev = curr;
curr = nextCurr;
}

return dummy.next;
}
}


## 题解2 - Recursion

### Java

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @return a ListNode
*/

return after;
}
}