[英]How to delete and return the last item in a linked list?
我的家庭作业需要我从链接列表中弹出最后一个项目,由于某种原因,一些测试用例可以工作,但有些不能用,我也不知道为什么。
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def __str__(self):
result = "("
node = self.head
if node != None:
result += str(node.data)
node = node.next
while node:
result += ", " + str(node.data)
node = node.next
result += ")"
return result
def remove_from_tail(self):
if self.head is None:
return None
prev = None
cur = self.head
while cur.next is not None:
prev = cur
cur = cur.next
if prev:
prev.next = None
return cur
#test case one is incorrect
my_list = LinkedList()
my_list.add(400)
print(my_list.remove_from_tail())
my_list.add(300)
print(my_list.remove_from_tail())
my_list.add(200)
print(my_list.remove_from_tail())
my_list.add(100)
print(my_list.remove_from_tail())
#should be 400 300 200 100 but instead I got 400 400 300 200
#test case two works fine
fruit = LinkedList()
fruit.add('cherry')
fruit.add('banana')
fruit.add('apple')
last_one = fruit.remove_from_tail()
print('Removed:', last_one)#got"Removed: cherry"
print(fruit)#(apple, banana)
我不知道当cur = self.head
和self.head
在删除400后应该指向300时,测试用例一失败的原因是什么。 因此,当我返回cur时,不应打印出两个400。任何帮助将不胜感激。
您的代码很好,问题是您每次添加后都调用remove_from_tail
,但是您要做的是调用add
直到添加所有元素,然后一个接一个地调用remove_from_tail
,这很好
my_list = LinkedList()
my_list.add(400)
my_list.add(300)
my_list.add(200)
my_list.add(100)
print(my_list.remove_from_tail())
print(my_list.remove_from_tail())
print(my_list.remove_from_tail())
print(my_list.remove_from_tail())
这个输出
400
300
200
100
另外,您的add
函数有点奇怪,通常我们会修复head并针对每个新元素遍历列表的末尾并追加它,但是在您的add
您正在更新head
上的每个元素并更新head。
而您的remove_from_tail
假定头部是固定的,并且我们要遍历到底,然后再进行更新,实际上
因此,运行添加4次后,列表为
head
100 -> 200 -> 300 -> 400
如您所料,尾巴也相应地从400
移至100
同样在remove_from_tail
函数中,您需要注意只有一个元素保留在列表中的情况,并且一旦添加原始测试用例也希望将其删除。
def remove_from_tail(self):
#If linked list is empty return None
if self.head is None:
return None
#If only one element in list, return that element and set head to None
elif self.head.next is None:
cur = self.head
self.head = None
return cur
#Otherwise iterate through the list
prev = None
cur = self.head
while cur.next is not None:
prev = cur
cur = cur.next
if prev:
prev.next = None
return cur
然后打印原始测试用例
400
300
200
100
以及
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.