删除给定位置的链表节点

时间:2017-09-03 03:49:05

标签: python linked-list

我使用递归解决了这个特殊问题,但是我无法使用 While循环 来解决这个问题。这是我的代码,错误和问题的链接:

https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-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'

3 个答案:

答案 0 :(得分:0)

  1. 您没有处理位置为0的基本条件
  2. 你没有在循环中递减position
  3. 实施删除逻辑时不需要额外的变量
  4. 法定警告List/list都是错误/无意义的名称,请避免使用它们。
  5. 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
    

    enter image description here

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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