leetcode24 Swap Nodes in Pairs
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于leetcode24 Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-24 Swap Nodes in Pairs
LeetCode 24 Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs