【发布时间】:2021-11-16 12:43:28
【问题描述】:
我正在尝试使用链接列表实现堆栈,但每当我尝试使用任何功能时,它都会返回一个额外的None。我不知道为什么会这样。在每次操作之后,我想要的输出不应包含关键字None。谁能告诉我这里出了什么问题?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.__head = None
self.__count = 0
def push(self, ele):
newNode = Node(ele)
newNode.next = self.__head
self.__head = newNode
self.__count = self.__count + 1
def pop(self):
if self.isEmpty() is True:
print("Hey! The stack is Empty")
return
else:
pop = self.__head.data
self.__head = self.__head.next
self.__count = self.__count - 1
return pop
def top(self):
if self.isEmpty() is True:
print("Hey! The stack is Empty")
return
else:
pop = self.__head.data
print(pop)
def size(self):
return self.__count
def isEmpty(self):
return self.__count == 0
s = Stack()
s.push(15)
print(s.top())
s.push(16)
print(s.pop())
print(s.top())
输出
15
无
16
无
16
15
无
【问题讨论】:
-
这是因为
s.top()没有返回任何东西。您正在打印它返回的内容,即无。一般来说,最好让函数只返回一个值,让调用者决定如何处理它,比如打印它。也就是说,从您的函数中删除打印语句。 -
(在这种情况下,将那些打印语句更改为返回语句)
标签: python python-3.x list data-structures stack