在python中删除链表中的节点 [英] Deleting a node in Linked List in python
问题描述
删除链表中的一个节点,这个实现有什么问题?:
To delete a node in a linked list, what is wrong with this implementation?:
def delete(self, val):
tmp = self.head
prev = None
while tmp:
if val == tmp.data:
self.size -= 1
if prev==None:
self.head = self.head.next
else:
prev.next = tmp.next
else:
prev = tmp
tmp = tmp.next
我看过的所有指南都说应该是:
All the guides I've looked at say it should be:
def delete(self, data):
tmp = self.head
prev = None
found = False
while tmp and not found:
if data == tmp.data:
found = True
else:
prev = tmp
tmp = tmp.next
if found:
self.size -= 1
if prev == None:
self.head = self.head.next
else:
prev.next = tmp.next
但我不明白为什么需要found.为什么发现是必要的?为什么这个实现更正确?
but I can't figure out why the found is needed. Why is the found necessary? Why is this implementation more correct?
另外,我在搜索时也遇到了同样的问题:
Additionally, I have the same trouble with search:
我的实现是:
def __contains__(self, data):
tmp = self.head
while tmp:
if data == tmp.data:
return True
else:
tmp = tmp.next
return False
但正确的实现是:
def __contains__(self, data):
tmp = self.head
found = False
while tmp and not found:
if data == tmp.data:
found = True
else:
tmp = tmp.next
return found
推荐答案
只要数据是唯一的,delete
就是相同的.因此,通常更好的是,从处理元素中对列表进行单独的循环.它更具可读性,更少嵌套.如果找不到 data
,最好给出一个错误:
The delete
s are identical as long as data is unique. So it is in general better, do separate looping through the list, from working on elements. It is more readable, and less nested. It would be still better, to give an error, if data
is not found:
def delete(self, data):
tmp = self.head
prev = None
while tmp:
if data == tmp.data:
break
prev = tmp
tmp = tmp.next
else:
raise ValueError('data not found')
self.size -= 1
if prev is None:
self.head = tmp.next
else:
prev.next = tmp.next
这篇关于在python中删除链表中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!