提问人:meallhour 提问时间:10/14/2023 更新时间:10/14/2023 访问量:31
从末尾找到第 k 个节点
Find kth node from the end
问:
我写了下面的函数 但是,一个隐藏的测试用例失败了。
请让我知道以下代码有什么问题。find kth node from the end.
def find_kth_from_end(l, k):
slow = l.head
fast = l.head
for _ in range(k):
fast = fast.next
if fast is None:
return l.head
while fast.next:
slow = slow.next
fast = fast.next
return slow.next
Error details
'NoneType' object has no attribute 'next'
答:
0赞
Ace Ataya
12/14/2023
#1
这是我的解决方案,但你必须导入sys:
def find_kth_from_end(list,index):
slow_pointer=fast_pointer=list.head
counter=0
for _ in range(index):
print("counter Pointer at: ", counter)
if fast_pointer:
print("Fast Pointer at: ", fast_pointer.value)
fast_pointer=fast_pointer.next
counter+=1
elif fast_pointer is None and counter<(index-1):
print("You have inputed a wrong index, you have given
extra",(index-counter))
sys.exit(0)
for _ in range(index):
if fast_pointer:
slow_pointer = slow_pointer.next
fast_pointer= fast_pointer.next
return slow_pointer
评论