我使用递归解决了这个特殊问题,但是我无法使用 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'
答案 0 :(得分:0)
答案 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