大佬1:采用递归的方式
# 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 not head or not head.next: #排除只有一个元素和只有两个元素的情况
return head
node1, node2 = head, head.next
tmp = self.swapPairs(node2.next) #接下来三行是精髓,利用递归方式将链表串联起来,细细品味
node2.next = node1
node1.next = tmp
return node2
自己:
# 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
"""
res = ListNode(-1)
res.next = head
parent = res
while True:
if parent.next and parent.next.next:
front = parent.next
rear = parent.next.next
parent.next = rear
front.next = rear.next
rear.next = front
parent = front
else:
break
return res.next