队列是一种抽象数据结构,具有以下特点:

(1)具有先进先出的特性(FIFO)

(2)拥有两种基本操作,即加入和删除,而且使用front和rear两个指针来分别指向队列的前端和末尾。

队列的基本操作

create   创建空队列

add       将新数据加入队列的末尾,返回新队列

delete   删除队列前端的数据,返回新队列

front     返回队列前端的值

empty  若队列为空,则返回 ‘真’,否则返回 ‘假’

实现queue有两种方式可以用数组和链表

1.我们先用数组实现队列,数组实现队列的好处在于算法相当简单,但是也有缺点,数组无法根据队列的实际需要动态申请,

只能声明固定的大小。现在我们声明一个有限容量的数组

MAXSIZE=4            #定义队列的大小
queue=[0]*MAXSIZE
front=-1
rear=-1

(1)开始时,我们将front与rear都设置-1,当front = rear时,为空队列

事件说明 front rear Q(0) Q(1) Q(2) Q(3)
空队列 -1 -1        

(2)当加入dataA , front=-1,rear=0,没加入一个元素,将rear值加1:

加入dataA -1      0       dataA                             

(3)加入dataB,dataC,front=-1,rear=2:

加入dataB、dataC -1            2               dataA         dataB        dabaC                         

(4)取出dataA,front=0,rear=2,每取出一个元素,将front的值加1:

取出dataA 0       2                dataB  dataC          

(5)加入dataD,front=0,rear=3,此时rear=MAXSIZE-1 ,表示队列已满

加入dataD     0         3                       dataB     dataC    dataD  

(6)取出dataB,front =1,rear=3:

取出dataB    1          3                               dataC    dataD 

对于以上队列操作,可以用Python语言实现一个队列的操作

import sys

MAX=10            #定义队列的大小
queue=[0]*MAX
front=rear=-1
choice=''
while rear<MAX-1 and choice !='e':
choice=input('[a]表示加入一个数值,[d]表示取出一个数值,[e]表示跳出此程序: ')
if choice=='a':
val=int(input('[请输入数值]: '))
rear+=1
queue[rear]=val
elif choice=='d':
if rear>front:
front+=1
print('[取出数值为]: [%d]' %(queue[front]))
queue[front]=0
else:
print('[队列已经空了]')
sys.exit(0)
else:
print() print('------------------------------------------')
print('[输出队列中的所有元素]:') if rear==MAX-1:
print('[队列已满]')
elif front>=rear:
print('没有')
print('[队列已空]')
else:
while rear>front:
front+=1
print('[%d] ' %queue[front],end='')
print()
print('------------------------------------------')
print()

执行结果如下

2用链表实现队列

我们以学生姓名和成绩的结构数据建立队列的节点,加上front和rear指针,这个类的声明如下:

class student:
def __init__(self):
self.name=' '*20
self.score=0
self.next=None front=student()
rear=student()
front=None
rear=None

在队列中加入新节点等于加入到队列的末端,而删除节点就是将此队列的最前端的节点删除。添加和删除操作如下:

def enqueue(name, score):  # 把数据加入队列
global front
global rear
new_data=student() # 分配内存给新元素
new_data.name=name # 给新元素赋值
new_data.score = score
if rear==None: # 如果rear为None,表示这是第一个元素
front = new_data
else:
rear.next = new_data # 将新元素连接到队列末尾 rear = new_data # 将rear指向新元素,这是新的队列末尾
new_data.next = None # 新元素之后无其他元素 def dequeue(): # 取出队列中的数据
global front
global rear
if front == None:
print('队列已空!')
else:
print('姓名:%s\t成绩:%d ....取出' %(front.name, front.score))
front = front.next # 将队列前端移到下一个元素

我们使用链表来设计一个队列的程序

class student:
def __init__(self):
self.name=' '*20
self.score=0
self.next=None front=student()
rear=student()
front=None
rear=None def enqueue(name, score): # 把数据加入队列
global front
global rear
new_data=student() # 分配内存给新元素
new_data.name=name # 给新元素赋值
new_data.score = score
if rear==None: # 如果rear为None,表示这是第一个元素
front = new_data
else:
rear.next = new_data # 将新元素连接到队列末尾 rear = new_data # 将rear指向新元素,这是新的队列末尾
new_data.next = None # 新元素之后无其他元素 def dequeue(): # 取出队列中的数据
global front
global rear
if front == None:
print('队列已空!')
else:
print('姓名:%s\t成绩:%d ....取出' %(front.name, front.score))
front = front.next # 将队列前端移到下一个元素 def show(): # 显示队列中的数据
global front
global rear
ptr = front
if ptr == None:
print('队列已空!')
else:
while ptr !=None: # 从front到rear遍历队列
print('姓名:%s\t成绩:%d' %(ptr.name, ptr.score))
ptr = ptr.next select=0
while True:
select=int(input('(1)加入 (2)取出 (3)显示 (4)离开 => '))
if select==4:
break
if select==1:
name=input('姓名: ')
score=int(input('成绩: '))
enqueue(name, score)
elif select==2:
dequeue()
else:
show()

执行如下:

python队列的实现的更多相关文章

  1. Python队列服务 Python RQ Functions from the __main__ module cannot be processed by workers.

    在使用Python队列服务 Python RQ 时候的报错: Functions from the __main__ module cannot be processed by workers. 原因 ...

  2. Python队列及在微信机器人中的应用

    本文来源于i春秋学院,未经允许严禁转载. 最近打算更新微信机器人,发现机器人的作者将代码改进了很多,但去掉了sqlite数据库,需要自己根据需求设计数据库,跟作者沟通得到的建议是为了防止消息并发导致数 ...

  3. python队列Queue

    Queue Queue是python标准库中的线程安全的队列(FIFO)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递 基本FIFO队列 clas ...

  4. Python 队列

    import multiprocessing import time if __name__ == '__main__': # 创建消息队列 # 3: 表示消息队列最大个数 queue = multi ...

  5. python队列基本使用

    Python queue队列 作用: 解耦:使程序直接实现松耦合,修改一个函数,不会有串联关系. 提高处理效率:FIFO = 现进先出,LIFO = 后入先出.   队列: 队列可以并发的派多个线程, ...

  6. python队列、线程、进程、协程

    目录: 一.queue 二.线程 基本使用 线程锁 自定义线程池 生产者消费者模型(队列) 三.进程 基本使用 进程锁 进程数据共享 默认数据不共享 queues array Manager.dict ...

  7. python队列、线程、进程、协程(转)

    原文地址: http://www.cnblogs.com/wangqiaomei/p/5682669.html 一.queue 二.线程 #基本使用 #线程锁 #自定义线程池 #生产者消费者模型(队列 ...

  8. python socket非阻塞及python队列Queue

    一. python非阻塞编程的settimeout与setblocking+select 原文:www.th7.cn/Program/Python/201406/214922.shtml 侧面认证Py ...

  9. Python|队列Queue

    一 前言 本文算是一次队列的学习笔记,Queue 模块实现了三种类型的队列,它们的区别仅仅是队列中元素被取回的顺序.在 FIFO 队列中,先添加的任务先取回.在 LIFO 队列中,最近被添加的元素先取 ...

随机推荐

  1. UVa10048_Audiophobia(最短路/floyd)(小白书图论专题)

    解题报告 题意: 求全部路中最大分贝最小的路. 思路: 类似floyd算法的思想.u->v能够有另外一点k.通过u->k->v来走,拿u->k和k->v的最大值和u-&g ...

  2. Canny算法源码,欢迎交流

    http://blog.csdn.net/jianxiong8814/article/details/1563109 http://blog.csdn.net/assuper/article/deta ...

  3. 【poj2774】Long Long Message

    用个分隔符将两个字符串连接起来,再用后缀数组求出height数组的值,找出一个height值最大并且i与i-1的sa值分别在两串字符中就好 #include<algorithm> #inc ...

  4. RPC和微服务

    1 什么是RPC 是remote procedure call的缩写. 2 什么是微服务 所谓的微服务就是说,把一个应用分解成一组小的服务,每个服务运行在自己的进程中.每个服务都可以单独部署,可以用自 ...

  5. linux 查看php扩展

    php -i |less 查看配置文件在哪里,编译参数 php -m |less 查看php加载的模块 less可以自由的上下访问,比more要灵活一点. 如果不使用less,信息一次性给予,不太好查 ...

  6. bzoj 1497(最大权闭合子图)

    1497: [NOI2006]最大获利 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 6410  Solved: 3099[Submit][Status] ...

  7. Spark 分布式环境---slave节点无法启动(已解决)

    soyo@soyo-VPCCB3S1C:~$ start-slaves.sh soyo-slave01: starting org.apache.spark.deploy.worker.Worker, ...

  8. E20180127-hm

    retain  vt. 保持; 留在心中,记住; 雇用; 付定金保留;

  9. [Swift]二分法的两种方式

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  10. c++ swap函数

    swap(a,b)也就是把a和b的值互换. 头文件:#include<algorithm>,swap要加using namespace std: