[英]No return in Delete Node Function Linked List - Python
I am learning linked list from scratch in Python and am trying to implement a music player using the same.我正在用 Python 从头开始学习链表,并尝试使用它来实现音乐播放器。 However, I was trying to create a function
delete_song()
to delete songs with reference from some coding sites and in most of them I saw the following piece of code:但是,我试图创建一个函数
delete_song()
来删除参考来自一些编码站点的歌曲,并且在大多数站点中我看到了以下代码:
def delete_song(self, song_name):
temp = self.head_node
if (temp is not None):
if (temp.data == song_name):
self.head_node = temp.next
temp = None
return
while(temp is not None):
if(temp.data == song_name):
break
prev = temp
temp = temp.next
if(temp == None):
return
prev.next = temp.next
temp = None
My questions are:我的问题是:
i) The data of Head Node is being stored in
temp
variable, and theif (temp is not None)
part is clear.i) Head Node 的数据存储在
temp
变量中,并且if (temp is not None)
部分是明确的。 But, how does thewhile (temp is not None)
loop traverse through the entire linked list (in case head does not match with key value) and search for the key value?但是,
while (temp is not None)
循环如何遍历整个链表(以防 head 与键值不匹配)并搜索键值?
ii) Why is there no return at the end of the
delete_song
function?ii) 为什么
delete_song
函数结束时没有返回?
My questions might be silly but I am unable to get an explanation to this logic.我的问题可能很愚蠢,但我无法解释这种逻辑。 Any help is appreciated!
任何帮助表示赞赏! TIA
TIA
Explained in comments so do check.在评论中解释,所以请检查。
while(temp is not None):
if(temp.data == song_name): # if match is found then break the loop
break
prev = temp # store current node as previous node
temp = temp.next # get the reference/value of next node in temp
"""
And at last node `temp.next` will be `None` which will be
stored in `temp` which will make `while` condition `False`
and it will come out.
"""
if(temp == None): # if traversal is over then temp will be None
return # and it will return or complete the execution
# In case it found the song in while loop then after break
# below code will be responsible for deleting that node as follows
prev.next = temp.next # store the next node value/reference in prev node
temp = None # delete the current node
As for there's no return at the end of the delete_song()
is because it does not want to return any value or notify it because it will be over whether if song is deleted or whether song is not found to be deleted.至于
delete_song()
最后没有返回是因为它不想返回任何值或通知它,因为是否删除歌曲或未找到删除歌曲都会结束。
For any clarification please comment如有任何澄清,请发表评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.