方法一:数组

    1. # 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
    2. #
    3. # 示例:
    4. #
    5. # 给定一个链表: 1->2->3->4->5, 和 n = 2.
    6. #
    7. # 当删除了倒数第二个节点后,链表变为 1->2->3->5.
    8. #
    9. #
    10. # 说明:
    11. #
    12. # 给定的 n 保证是有效的。
    13. #
    14. # 进阶:
    15. #
    16. # 你能尝试使用一趟扫描实现吗?
    17. # Related Topics 链表 双指针
    18. # 👍 1169 👎 0
    19. # leetcode submit region begin(Prohibit modification and deletion)
    20. # Definition for singly-linked list.
    21. class ListNode(object):
    22. def __init__(self, val=0, next=None):
    23. self.val = val
    24. self.next = next
    25. class Solution(object):
    26. def removeNthFromEnd(self, head, n):
    27. """
    28. :type head: ListNode
    29. :type n: int
    30. :rtype: ListNode
    31. """
    32. curr = head
    33. cache = []
    34. while curr:
    35. cache.append(curr)
    36. curr = curr.next
    37. currIndex = n * (-1)
    38. if n == len(cache):
    39. head = head.next
    40. else:
    41. cache[currIndex - 1].next = cache[currIndex].next
    42. return head
    43. # leetcode submit region end(Prohibit modification and deletion)

    方法二:快慢指针

    1. class Solution(object):
    2. def removeNthFromEnd(self, head, n):
    3. """
    4. :type head: ListNode
    5. :type n: int
    6. :rtype: ListNode
    7. """
    8. dummy = ListNode(0, head)
    9. p1 = head
    10. p2 = dummy
    11. for i in range(n):
    12. p1 = p1.next
    13. while p1:
    14. p1 = p1.next
    15. p2 = p2.next
    16. p2.next = p2.next.next
    17. return dummy.next