【发布时间】:2019-05-12 05:15:51
【问题描述】:
我的家庭作业需要我从链表中弹出最后一项,由于某种原因,一些测试用例有效,但有些无效,我不知道为什么。
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。任何帮助将不胜感激。
【问题讨论】:
标签: python python-3.x linked-list nodes