栈与队列怎么在Python中使用

发布时间:2021-04-07 16:22:47 作者:Leah
来源:亿速云 阅读:92

本篇文章给大家分享的是有关栈与队列怎么在Python中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

Python常见数据结构之-栈

首先,栈是一种数据结构。具有后进先出特性。

#栈的实现
class Stack():
  def __init__(self,size):
    self.stack=[]
    self.size=size
    self.top=-1
  def push(self,content):
    if self.Full():
      print "Stack is Full"
    else:
      self.stack.append(content)
      self.top=self.top+1
  def out(self):
    if self.Empty():
      print "Stack is Empty"
    else:
      self.top-=1
  def Full(self):
    if self.top==self.size-1:
      return True
    else:
      return False
  def Empty(self):
    if self.top==-1:
      print "Stack is Empty"
if __name__=="__main__":
  q=Stack(7)
  q.Empty()
  q.push("hello")
  q.Empty()

运行结果:

Stack is Empty

Python常见数据结构之-队列

队列是一种先进先出的数据结构。

#队列的实现
class Queue():
  def __init__(self,size):
    self.queue=[]
    self.size=size
    self.head=-1
    self.tail=-1
  def Empty(self):
    if self.head==self.tail:
      return True
    else:
      return False
  def Full(self):
    if self.tail-self.head==self.size-1:
      return True
    else:
      return False
  def enQueue(self,content):
    if self.Full():
      print "Queue is Full"
    else:
      self.queue.append(content)
      self.tail+=1
  def outQueue(self):
    if self.Empty():
      print "Queue is Empty!"
    else:
      self.head+=1
if __name__=="__main__":
  q=Queue(6)
  print q.Empty() # True
  q.enQueue("123")
  print q.Empty() #False
  q.outQueue()

运行结果:

True
False

以上就是栈与队列怎么在Python中使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 数据结构--栈与队列
  2. c++中栈与队列的实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何在微信小程序中使用公用参数与公用方法

下一篇:使用node.js如何连接mysql

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》