赞
踩
- class Solution(object):
- def reverseBetween(self, head, left, right):
- """
- :type head: ListNode
- :type left: int
- :type right: int
- :rtype: ListNode
- """
- right = right -1
- left = left -1
-
- while( right-left>=0 ):
- print(right-left)
- # 左侧节点
- l = head
- for i in range(left):
- l = l.next
- # 右侧节点
- r = head
- for i in range(right):
- r = r.next
- # print(l.val, r.val)
- l.val, r.val = r.val, l.val
- right = right-1
- left = left+1
- print(head)
- return head
上面的方法其实有那么些问题,更ok的应该是下面这种
- class Solution:
- def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
- # 设置 dummyNode 是这一类问题的一般做法
- dummy_node = ListNode(-1)
- dummy_node.next = head
- pre = dummy_node
- for _ in range(left - 1):
- pre = pre.next
-
- cur = pre.next
- for _ in range(right - left):
- next = cur.next
- cur.next = next.next
- next.next = pre.next
- pre.next = next
- return dummy_node.next
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。