leetcode24-swap nodes in pairs

题目

交换链表中每相邻的两个结点

分析

对于 a-b-c-d,交换后为b-a-d-c

python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class (object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

res = ListNode(0)
res.next = head
cur = res
while cur.next and cur.next.next:
a = cur.next
b = cur.next.next
cur.next, b.next, a.next = b, a, b.next

# cur.next = b
# b.next = a
# a.next = c
cur = a
return res.next