詳解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內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!