【发布时间】:2020-12-30 19:02:08
【问题描述】:
我正在使用 Python 在链表的头部实现插入。我引用了这个guide。对于案例 2,我发现我必须添加 return self.head 以使驱动程序代码正确插入头部,否则它不会终止。这是为什么?我认为第一行就足够了,因为我正在调用此方法来修改链表。为什么我需要返回?
这是在节点之前插入的代码:
class LinkedList:
# note nodes = Node set the default (no argument) initialization
def __init__(self, nodes = None):
self.head = None
if nodes is not None:
# .pop(index) method remove the element from an array-like container and return it
node = Node(nodes.pop(0))
self.head = node
# loop through the rest elements in nodes (2nd now became the 1st in nodes)
for elem in nodes:
node.next = Node(elem)
node = node.next
def insert_before(self, targetn_data, newn):
# case1: empty list
if self.head is None:
raise Exception('empty llist')
# case2: insert before head (newn becomes new head)
if targetn_data == self.head.data:
print(f'inserting {newn} at the head')
newn.next = self.head
self.head = newn
################# Why? ##################
return self.head
#########################################
# case3: in between. use runner technique
...
驱动代码:
def main():
nodes = [1, 2, 3, 4, 5, 6]
# instantiate a linked list using __init__ method we defined
llist = LinkedList(nodes)
# insert_before driver code
llist.insert_before(1, Node(100))
llist.insert_before(6, Node(90))
print(f'prints out the llist after insert_before: \n {llist}\n')
【问题讨论】:
-
嗯,你当然不需要回头,只需要
return。您只需要在此时结束函数,否则您将继续处理案例 3。您可以将案例 3 轻松包装在else中,但我认为return更可爱。 -
谢谢,这是有道理的。我认为这只是我引用的链接中的一个错字。
标签: python algorithm data-structures linked-list