源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现基本数据结构中栈的操作示例

  • 时间:2021-12-27 23:34 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python实现基本数据结构中栈的操作示例
本文实例讲述了Python实现基本数据结构中栈的操作。分享给大家供大家参考,具体如下:
#! /usr/bin/env python
#coding=utf-8
#Python实现基本数据结构---栈操作
class Stack(object):
  def __init__(self,size):
    self.size = size
    self.stack = []
    self.top = 0#初始化,top=0时则为空栈
  def push(self,x):
    if self.stackFull():#进栈之前检查栈是否已满
      raise Exception("overflow !")
    else:
      self.stack.append(x)
      self.top=self.top+1#push进去的第一个元素下标为1
  def pop(self):
    if self.stackEmpty():
      raise Exception("underflow !")
    else:
      self.top=self.top-1
      return self.stack.pop()#利用Python内建函数pop()实现弹出
  def stackEmpty(self):
    if self.top == 0:#判断栈空
      return True
    else:
      return False
  def stackFull(self):
    if self.top == self.size:#判断栈满!!!
      return True
    else:
      return False
if __name__ == '__main__':
  print "编程素材网测试结果:"
  s=Stack(10)
  for i in range(3):
    s.push(i)
  print s.stack
  print s.pop()
  print s.stack
  print s.pop()
  print s.pop()
  print s.stack
  print s.stackEmpty()
  print s.stackFull()
  for i in range(10):
    s.push(i)
  print s.stackFull()

运行结果: [img]http://files.jb51.net/file_images/article/201712/2017124111601688.png?2017114111614[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/946.htm]Python加密解密算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部