当前位置:   article > 正文

python刷题-单链表_dummy = listnode(0, head)

dummy = listnode(0, head)

题目:

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

力扣

  1. class ListNode:
  2. def __init__(self, val=0, next=None):
  3. self.val = val
  4. self.next = next
  5. # 个人题解:双指针
  6. class Solution:
  7. def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
  8. # 这里可以构造一个前驱节点指向头结点,会少一些判断情况,具体看官方题解
  9. node = head
  10. pre = node
  11. arrow = node.next
  12. for i in range(n-1):
  13. arrow = arrow.next
  14. while arrow:
  15. pre = node
  16. node = node.next
  17. arrow = arrow.next
  18. if head == node:
  19. return head.next
  20. else:
  21. pre.next = node.next
  22. del node
  23. return head
  24. # 暴力
  25. class Solution:
  26. def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
  27. def getLength(head: ListNode) -> int:
  28. length = 0
  29. while head:
  30. length += 1
  31. head = head.next
  32. return length
  33. dummy = ListNode(0, head)
  34. length = getLength(head) # 获取链表长度
  35. cur = dummy
  36. for i in range(1, length - n + 1):
  37. cur = cur.next
  38. cur.next = cur.next.next
  39. return dummy.next
  40. # 栈实现
  41. class Solution:
  42. def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
  43. dummy = ListNode(0, head)
  44. stack = list()
  45. cur = dummy
  46. while cur:
  47. stack.append(cur)
  48. cur = cur.next
  49. for i in range(n):
  50. stack.pop()
  51. prev = stack[-1]
  52. prev.next = prev.next.next
  53. return dummy.next

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

闽ICP备14008679号