首页 > 解决方案 > 从列表末尾删除第 N 个节点(Leetcode)?- Python

问题描述

链接 - https://leetcode.com/problems/remove-nth-node-from-end-of-list/

我的方法:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        h = head
        td = h

        c = 0
        while head.next is not None:
            c+=1
            print(c,n)
            if c>n:
                td = td.next
            head = head.next
        if c + 1 != n:
            td.next = td.next.next
        return h

它在 [1,2] 和 n = 2 之类的边界情况下失败,有什么方法可以修改它以使其适用于所有边界情况并被接受?(我知道我们可以使用慢速和快速指针来解决这个问题)

标签: pythonlinked-listreverse

解决方案


如果您有兴趣,我已经发布了一个替代解决方案。

class Solution:
    def removeNthFromEnd(self, head, n):
        fast = slow = head
        for _ in range(n):
            fast = fast.next
        if not fast:
            return head.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

推荐阅读