详解python数据结构之栈stack
前言
栈(Stack)是一种运算受限的线性表。
按照先进后出(FILO,First In Last Out)的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶。栈只能在一端进行插入和删除操作。
文章内容包含:
(1)栈的基本格式
(2)压栈 push_stack
(3)出栈 pop_stack
(4)取栈顶 peek_stack
一、栈的基本格式
class Stack(): def __init__ (self,size): self.size = size #栈空间大小 self.top = -1 #栈中进入一个数据 top 加 1 self.stack = [] def display_stack(self):#栈stack的打印 print(self.stack) if __name__ == "__main__": stack = Stack(5) #设定栈空间 stack.display_stack() #打印栈数据
二、进栈与压栈 push_stack
class Stack(): def __init__ (self,size): self.size = size self.top = -1 self.stack = [] #进栈数据列表 def display_stack(self): print(self.stack) def push_stack(self,data): if len(self.stack ) >= self.size: #当数据数量大于设置的空间,则栈溢出 print("stack over flow!") return self.stack.append(data) #没有栈溢出就将数据追加到列表中 self.top += 1 #栈中每增加一个数据就加 1 if __name__ == "__main__": stack = Stack(5) stack.push_stack(0) stack.push_stack(1) stack.push_stack(2) stack.push_stack(3) stack.push_stack(4) stack.push_stack(5) #stack空间是 5,这里进栈数据时 6 个,即提示栈溢出stack over flow! stack.display_stack()
执行结果:
三、出栈 pop_stack
class Stack(): def __init__ (self,size): self.size = size self.top = -1 self.stack = [] #进栈数据列表 def display_stack(self): print(self.stack) def push_stack(self,data): if len(self.stack ) >= self.size: print("stack over flow!") return self.stack.append(data) self.top += 1 def pop_stack(self): if self.top <= -1: #当top小于等于初始值 -1 时说明stack数据列表为空 print("stack is empty!") return ret = self.stack.pop() #stack数据列表不为空就取出最后进的值,列表数据数量就少一个 self.top -= 1 return ret if __name__ == "__main__": stack = Stack(5) stack.push_stack(0) stack.push_stack(1) stack.push_stack(2) stack.push_stack(3) stack.push_stack(4) stack.display_stack() #进栈数据有 5 个,出栈函数调用了 6 次,就出现了提示stack is empty! ret = stack.pop_stack() print(ret) stack.display_stack() ret = stack.pop_stack() print(ret) stack.display_stack() ret = stack.pop_stack() print(ret) stack.display_stack() ret = stack.pop_stack() print(ret) stack.display_stack() ret = stack.pop_stack() print(ret) stack.display_stack() ret = stack.pop_stack() print(ret) stack.display_stack()
执行结果:
四、取栈顶 peek_stack
class Stack(): def __init__ (self,size): self.size = size self.top = -1 self.stack = [] def display_stack(self): print(self.stack) def push_stack(self,data): if len(self.stack ) >= self.size: print("stack over flow!") return self.stack.append(data) self.top += 1 def peek_stack(self): if self.top == -1: #当栈内没有数据时 提示 stack is empty! print("stack is empty!") return peek = self.stack[self.top] #栈不为空时,将栈顶的数据提取出来 return peek if __name__ == "__main__": stack = Stack(5) stack.push_stack(0) stack.push_stack(1) stack.push_stack(2) stack.push_stack(3) stack.push_stack(4) stack.push_stack(5) stack.display_stack() peek = stack.peek_stack() print(peek)
执行结果:
到此这篇关于详解python数据结构之栈stack的文章就介绍到这了,更多相关python 栈stack内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)