本文以实例形式展示了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: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())

感兴趣的读者可以动手测试一下本文所述实例代码,相信会对大家学习Python能有一定的收获。