swap nodes in pairs

用递归的想法比较容易做。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class (object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
cur = head
next = head.next
next_head = head.next.next
next.next = cur
cur.next = self.swapPairs(next_head)
return next