我正在尝试创建一个prepend方法,该方法获取该值并将其插入链接列表中的头和下一个值之间,现在我就在这里,它只打印一个值<;因为print语句,然后它只打印1:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
# Move to the tail (the last node)
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
def prepend(self,value):
if self.head is None:
self.head = Node(value)
return
else:
holder = None
self.head.next = holder
#holder.next = holder
print(holder)
return
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(4)
linked_list.prepend(5)
node = linked_list.head
while node:
print(node.value)
node = node.next
你知道怎么做或修正我的逻辑吗?请一步一步地向我解释你是如何想出解决方案的。 我是初学者
以下是您可以执行的操作:
请注意,即使您的append方法是正确的,它也不是有效的,因为您必须查看linkedlist中的所有节点才能追加元素(因此,对于append插入来说是O(n)),而您所称的prepend更有效,因为它是在linkedlist中插入元素的O(1)
相关问题 更多 >
编程相关推荐