栈的基本原理是先进后出,每次只能最先取到栈顶的元素,然后栈的结构得到改变。
# 实现栈,需要节点类和栈类
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):
if not self.top:
return None
else:
return self.top.data
# 判断栈是否为空
def isEmpty(self):
if not self.peek():
return True
else:
return False