这题要求是常数空间,不能修改值,只能修改node,所以直接在node上进行操作。代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head:
if head.next:
b = head.next
head.next = head.next.next
b.next = head
head = b
print head.val
left = head.next
while left.next and left.next.next:
b = left.next
left.next = b.next
c = left.next.next
left.next.next = b
b.next = c
left = left.next.next
return head