本文以實例形式展示了Python算法中棧(stack)的實現,對于學習數據結構域算法有一定的參考借鑒價值。具體內容如下:
1.棧stack通常的操作:
Stack() 建立一個空的棧對象
push() 把一個元素添加到棧的最頂層
pop() 刪除棧最頂層的元素,并返回這個元素
peek() 返回最頂層的元素,并不刪除它
isEmpty() 判斷棧是否為空
size() 返回棧中元素的個數
2.簡單案例以及操作結果:
Stack Operation Stack Contents Return Value s.isEmpty() [] True s.push(4) [4] s.push('dog') [4,'dog'] s.peek() [4,'dog'] 'dog' s.push(True) [4,'dog',True] s.size() [4,'dog',True] 3 s.isEmpty() [4,'dog',True] False s.push(8.4) [4,'dog',True,8.4] s.pop() [4,'dog',True] 8.4 s.pop() [4,'dog'] True s.size() [4,'dog'] 2
這里使用python的list對象模擬棧的實現,具體代碼如下:
#coding:utf8class Stack: """模擬棧""" def __init__(self): self.items = [] def isEmpty(self): return len(self.items)==0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if not self.isEmpty(): return self.items[len(self.items)-1] def size(self): return len(self.items) s=Stack()print(s.isEmpty())s.push(4)s.push('dog')print(s.peek())s.push(True)print(s.size())print(s.isEmpty())s.push(8.4)print(s.pop())print(s.pop())print(s.size())
感興趣的讀者可以動手測試一下本文所述實例代碼,相信會對大家學習Python能有一定的收獲。
新聞熱點
疑難解答