欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python算法之棧(stack)的實現(xiàn)

 更新時間:2014年08月18日 11:17:40   投稿:shichen2014  
這篇文章主要介紹了Python算法之棧(stack)的實現(xiàn),非常實用,需要的朋友可以參考下

本文以實例形式展示了Python算法中棧(stack)的實現(xiàn),對于學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)域算法有一定的參考借鑒價值。具體內(nèi)容如下:

1.棧stack通常的操作:

Stack() 建立一個空的棧對象
push() 把一個元素添加到棧的最頂層
pop() 刪除棧最頂層的元素,并返回這個元素
peek()  返回最頂層的元素,并不刪除它
isEmpty()  判斷棧是否為空
size()  返回棧中元素的個數(shù)

2.簡單案例以及操作結(jié)果:

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對象模擬棧的實現(xiàn),具體代碼如下:

#coding:utf8
class 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())

感興趣的讀者可以動手測試一下本文所述實例代碼,相信會對大家學(xué)習(xí)Python能有一定的收獲。

相關(guān)文章

最新評論