Python 在给定位置删除链表节点

Python 在给定位置删除链表节点,python,linked-list,Python,Linked List,我已经用递归解决了这个特殊的问题,但是我不能用While循环解决这个问题。以下是我的代码、错误和问题的链接: 代码 错误 您没有处理位置为0的基本条件 你没有减少循环中的位置 在实现删除逻辑时,不需要额外的变量 法定警告列表/列表都是不好的/没有意义的名称,请避免使用它们。 您应该发布能够再现错误的代码的最低版本,而不仅仅是Delete函数。此外,还缺少一些缩进。位置递减在哪里?list是一个错误的变量名,因为它隐藏了内置的list构造函数。 def Delete(head, position)

我已经用递归解决了这个特殊的问题,但是我不能用While循环解决这个问题。以下是我的代码、错误和问题的链接:

代码

错误

您没有处理位置为0的基本条件 你没有减少循环中的位置 在实现删除逻辑时,不需要额外的变量 法定警告列表/列表都是不好的/没有意义的名称,请避免使用它们。
您应该发布能够再现错误的代码的最低版本,而不仅仅是Delete函数。此外,还缺少一些缩进。位置递减在哪里?list是一个错误的变量名,因为它隐藏了内置的list构造函数。
def Delete(head, position):
    list=head
    while(position-1):
        head=head.next
        position=position-1
    add=head.next
    head.next=add.next
    return list
Traceback (most recent call last):
File "solution.py", line 76, in <module>
head = Delete(L1.head, p)
File "solution.py", line 60, in Delete
head=head.next
AttributeError: 'NoneType' object has no attribute 'next'
def Delete(head, position):
    temp = head
    if position == 0:
        return temp.next

    while position - 1 > 0:
        head = head.next
        position -= 1
    head.next = head.next.next
    return temp
def delete(head, position):
    if position:
        # step ahead to node preceding the target
        here = head
        for _ in range(position - 1):
            here = here.next
        # snip the target out of the list
        here.next = here.next.next
        return head
    else:
        # special case - remove head node
        return head.next
def Delete(head, position):
    current = head
    previous = None
    found = False
    count = 0

    while not found:
        if count == position:
            found = True
        else:
            previous = current
            current = current.next
        count += 1

    # previous hasn't changed, node we're looking for is the head
    if previous == None:
        head = current.next
    else: # we're somewhere between head and tail
        previous.next = current.next

    return head