How to create generic stack in python? My stack implementation in 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
Now I am putting objects of class Node, but how implement generic Stack so that I can put there anything. For example, if I want create new type of nodes
class NodeWithMin:
def __init__(self, value, minval):
self.data = value
self.minval = minval
And be able create stack based on these type of nodes, so it should be something like this (of course it does not work):
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))
any idea?
EDIT: it did not work because I have next error:
unbound method push() must be called with Stack instance as first argument (got NodeWithMinV2 instance instead)
I missed self
list?list.append(element)to push,element = list.pop()to pop.Nodeclass to wrap Python objects. This seems like a Java programmer refusing to use Python's dynamic typing.