原题链接:https://leetcode.com/problems/swap-nodes-in-pairs/
解题思路:在head前添加一个node,第一步,将pre指向该对pair的第二个,第二步,将cur指向下一对pair的第一个,第三步,将该对pair的第二个指向第一个。
代码:
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = ListNode(0)
pre.next = head
current = head
head = pre
while current:
pre.next = current.next
current.next = current.next.next
pre.next.next = current
pre = pre.next.next
current = current.next
return head.next