python 栈的理解与使用
2021-05-29 10:01
class Node(object):
def __init__(self, data, next = None):
self.data = data
self.next = nextclass Stack(object):
def __init__(self, top = None):
self.top = topdef push(self,data):
#创建新的节点放到栈顶
self.top = Node(data, self.top)def pop(self):
#拿出栈顶元素,原来的栈发生改变
if self.top is None:
return None
data = self.top.data
self.top = self.top.next
return datadef peek(self):
#查看栈顶元素,原来的栈不变
return self.top.data if self.top is not None else Nonedef isEmpty(self):
return self.peek() is None
if __name__ == "__main__":
stack = Stack()