Python的队列
2016-01-02 22:58
627 查看
# -*- coding:utf-8 -*- ''' 定义一个队列Queue ''' class Queue(object): def __init__(self,size): self.queue = [] self.size = size self.head = -1 self.tail = -1 def isEmpty(self): if self.head == self.tail: return True else: return False def isFull(self): if self.tail - self.head + 1 == self.size: return True else: return False def inQueue(self,content): if self.isFull(): print "Queue is full,can't contain any item any more." else: self.queue.append(content) #入队时,将元素新增到队列中 self.tail += 1 #入队时,队首指针不变,队尾指针递增1 def outQueue(self): if self.isEmpty(): print "Queue is empty,no item need to out." else: self.queue.pop(0) #出队列:每次出队列后删除队首元素 self.head += 1 #出队列时,队首指针递增1,对位指针不变 def display(self): print "Queue = ",self.queue print "Size = ",len(self.queue) print "Head = %d,Tail = %d\n"%(self.head,self.tail) #测试出队入队操作、队满时入队、队空时出队 q = Queue(4) print "----------入队操作----------" for i in range(5): q.inQueue(i) q.display() print "----------出队操作----------" for i in range(6): q.outQueue() q.display()
”’
运行结果:
———-入队操作———-
Queue = [0]
Size = 1
Head = -1,Tail = 0
Queue = [0, 1]
Size = 2
Head = -1,Tail = 1
Queue = [0, 1, 2]
Size = 3
Head = -1,Tail = 2
Queue is full,can’t contain any item any more.
Queue = [0, 1, 2]
Size = 3
Head = -1,Tail = 2
Queue is full,can’t contain any item any more.
Queue = [0, 1, 2]
Size = 3
Head = -1,Tail = 2
———-出队操作———-
Queue = [1, 2]
Size = 2
Head = 0,Tail = 2
Queue = [2]
Size = 1
Head = 1,Tail = 2
Queue = []
Size = 0
Head = 2,Tail = 2
Queue is empty,no item need to out.
Queue = []
Size = 0
Head = 2,Tail = 2
Queue is empty,no item need to out.
Queue = []
Size = 0
Head = 2,Tail = 2
Queue is empty,no item need to out.
Queue = []
Size = 0
Head = 2,Tail = 2
”’
相关文章推荐
- Android Native 绘图方法
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例