当前位置:   article > 正文

leetcode 92. 反转链表 II

leetcode 92. 反转链表 II
  1. class Solution(object):
  2. def reverseBetween(self, head, left, right):
  3. """
  4. :type head: ListNode
  5. :type left: int
  6. :type right: int
  7. :rtype: ListNode
  8. """
  9. right = right -1
  10. left = left -1
  11. while( right-left>=0 ):
  12. print(right-left)
  13. # 左侧节点
  14. l = head
  15. for i in range(left):
  16. l = l.next
  17. # 右侧节点
  18. r = head
  19. for i in range(right):
  20. r = r.next
  21. # print(l.val, r.val)
  22. l.val, r.val = r.val, l.val
  23. right = right-1
  24. left = left+1
  25. print(head)
  26. return head

上面的方法其实有那么些问题,更ok的应该是下面这种

  1. class Solution:
  2. def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
  3. # 设置 dummyNode 是这一类问题的一般做法
  4. dummy_node = ListNode(-1)
  5. dummy_node.next = head
  6. pre = dummy_node
  7. for _ in range(left - 1):
  8. pre = pre.next
  9. cur = pre.next
  10. for _ in range(right - left):
  11. next = cur.next
  12. cur.next = next.next
  13. next.next = pre.next
  14. pre.next = next
  15. return dummy_node.next

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/535231
推荐阅读
相关标签
  

闽ICP备14008679号