# [LeetCode] 24. Swap Nodes in Pairs 成对交换节点

2021年09月15日 阅读数：1

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

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

Java：指针

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

while (r != null && r.next != null && r.next.next != null) {
ListNode p = r.next.next;
ListNode q = r.next;
ListNode next = p.next;
p.next = q;
q.next = next;
r.next = p;
p = q.next == null ? null : q.next.next;
q = q.next;
r = r.next.next;
}

}
}　　```

Python: Iterationcode

```class ListNode:
def __init__(self, x):
self.val = x
self.next = None

def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)

class Solution:
# @param a ListNode
# @return a ListNode
dummy = ListNode(0)
current = dummy
while current.next and current.next.next:
next_one, next_two, next_three = current.next, current.next.next, current.next.next.next
current.next = next_two
next_two.next = next_one
next_one.next = next_three
current = next_one
return dummy.next```

C++: Iterationorm

```class Solution {
public:
ListNode *dummy = new ListNode(-1), *pre = dummy;
while (pre->next && pre->next->next) {
ListNode *t = pre->next->next;
pre->next->next = t->next;
t->next = pre->next;
pre->next = t;
pre = t->next;
}
return dummy->next;
}
};
```

C++: Recursion

```class Solution {
public:
return t;
}
};　```