欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现基本数据结构中队列的操作方法示例

程序员文章站 2022-07-05 13:14:50
本文实例讲述了Python实现基本数据结构中队列的操作方法。分享给大家供大家参考,具体如下: #! /usr/bin/env python #coding=ut...

本文实例讲述了Python实现基本数据结构中队列的操作方法。分享给大家供大家参考,具体如下:

#! /usr/bin/env python
#coding=utf-8
class Queue(object):
  def __init__(self,size):
    self.size=size
    self.head=-1 #初始化队头
    self.tail=-1 #初始化队尾
    self.queue=[]
  def EnQueue(self,x):
    if self.IsFull():#如果试图往满队列插入元素,则发生上溢
      raise Exception("overflow !")
    else:
      self.queue.append(x)
      self.tail += 1 #往队列中加入元素是在尾部进行
  def DeQueue(self):
    if self.IsEmpty():#如果试图从空队列删除元素,则发生下溢
      raise Exception("underflow !")
    else:
      self.head += 1#从队列中删除元素在队头进行,将队头后移
      return self.queue.pop(0)#利用内建函数pop()将队头弹出
  def IsFull(self):#判断队列满
    #return (self.tail+1)%self.size == self.head
    return self.tail-self.head+1==self.size
  def IsEmpty(self):#判断队列空!!!
    return self.head == self.tail
if __name__ == '__main__':
  print "测试结果:"
  q=Queue(10)
  for i in range(3):
    q.EnQueue(i)
  print q.queue
  print q.DeQueue()
  print q.queue
  print q.DeQueue()
  print q.IsEmpty()
  print q.DeQueue()
  print q.IsEmpty()
  print q.queue
  for i in range(9):
    q.EnQueue(i)
  print q.queue
  print q.IsFull()

运行结果:

Python实现基本数据结构中队列的操作方法示例

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。