如何在python中创建通用堆栈?
python堆栈中的实现:class Node(object):
def __init__(self, d):
self.data = d
self.nextNode = None
class Stack(object):
def __init__(self):
self.top = None
def push(self, item):
newNode = Node(item)
newNode.nextNode = self.top
self.top = newNode
def pop(self):
if self.top == None:
return None
item = self.top.data
self.top = self.top.nextNode
return item
现在我要放的是类Node的对象,但是如何实现泛型堆栈以便我可以在其中放置任何东西。例如,如果要创建新类型的节点
^{pr2}$
并且能够基于这些类型的节点创建堆栈,因此应该是这样的(当然它不起作用):class StackWithMin(qs.Stack):
def push(self, val):
if self.peek() != None:
minval = min(self.peek().value, val)
else:
minval = val
qs.Stack.push(NodeWithMinV2(val, minval))
有什么想法吗?在
编辑:
它不起作用,因为我有下一个错误:unbound method push() must be called with Stack instance as first argument (got NodeWithMinV2 instance instead)
我错过了self