python 栈的理解与使用

2021-05-29 10:01

阅读:632

class Node(object):
def __init__(self, data, next = None):
self.data = data
self.next = next

class Stack(object):
def __init__(self, top = None):
self.top = top

def 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 data

def peek(self):
#查看栈顶元素,原来的栈不变
return self.top.data if self.top is not None else None

def isEmpty(self):
return self.peek() is None


if __name__ == "__main__":
stack = Stack()


评论


亲,登录后才可以留言!