1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def swapPairs(self, head: ListNode) -> ListNode:
 9         node = ListNode(-1)
10         node.next = head
11         pre = node
12         while pre.next != None and pre.next.next != None:
13             l1,l2 = pre.next,pre.next.next
14             nexNode = l2.next
15             l1.next = nexNode
16             l2.next = l1
17             pre.next = l2
18             pre = l1
19         return node.next

交换链表中相邻的两个节点,注意12行的判断条件。

posted on 2019-06-22 08:36  Sempron2800+  阅读(132)  评论(0编辑  收藏  举报