码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode24 Swap Nodes in Pairs

时间:2020-02-07 18:27:44      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:val   nbsp   判断   不为   link   solution   first   class   color   

 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

 

leetcode24 Swap Nodes in Pairs

标签:val   nbsp   判断   不为   link   solution   first   class   color   

原文地址:https://www.cnblogs.com/yawenw/p/12273826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!