leetcode24 Swap Nodes in Pairs

 1 """
 2 Given a linked list, swap every two adjacent nodes and return its head.
 3 You may not modify the values in the list's nodes, only nodes itself may be changed.
 4 Example:
 5 Given 1->2->3->4, you should return the list as 2->1->4->3.
 6 """
 7 class ListNode:
 8     def __init__(self, x):
 9         self.val = x
10         self.next = None
11 
12 class Solution:
13     def swapPairs(self, head):
14         first = ListNode(0)
15         first.next = head
16         if head == None or head.next == None:
17             return head
18         p = first          #三个指针,p代表previous前结点,m代表medium中结点,l代表last后结点
19         m = head
20         l = head.next
21         while m and l:           #bug只写了 while l:
22             m.next = l.next      #因为下面是if句,此处还应再判断一下m! = None
23             l.next = m
24             p.next = l
25             p = m
26             m = p.next
27             if m != None:        #BUG 没写if判断句,首先要保证m != None,才能保证m.next不为None
28                 l = m.next
29         return first.next

 

posted @ 2020-02-07 17:39  yawenw  阅读(117)  评论(0编辑  收藏  举报