Python-数组实现循环队列和非循环队列

Judy ·
更新时间:2024-11-15
· 703 次阅读

 什么是队列?

 队列就是只能在一端插入,而在另一端删除的线性表,故队列又称为先进先出队列

队列类型有哪些?

循环队列和顺序队列

 队列的存储实现方式有哪些?

顺序存储(数组)和链式存储(链表),此博文描述的是数组的实现(后续更新链表实现)

 代码实现

初始化队列:初始化一个size长度的队列,队列的值都为0

判断队列是否已满:队列满,不可插入队列

判断队列是否为空:队列空,没有数据可以出队

入队:将数据item插入队列

出队:将对头元素从队列中删除并返回的值

class Queue: """非循环队列""" def __init__(self, size): self.size = size self.front = -1 self.rear = -1 self.queue = [0]*size def enqueue(self, item): if self.isFull(): raise Exception('队列满') else: self.rear += 1 self.queue[self.rear] = item def dequeue(self): if self.isEmpty(): raise Exception('队列空') else: self.front += 1 data = self.queue[self.front] self.queue[self.front] = 0 return data def isFull(self): return self.rear - self.front == self.size def isEmpty(self): return self.rear == self.front def showQueue(self): print(self.queue) class circleQueue: """循环队列""" def __init__(self, size): self.size = size self.front = 0 self.rear = 0 self.queue = [0]*size def enQueue(self, item): """进队列,将值放进队列""" if self.isFull(): raise Exception('队列满') else: self.rear = (self.rear+1) % self.size self.queue[self.rear] = item def deQueue(self): """出队列,并返回出队列的值""" if self.isEmpty(): raise Exception('队列空') else: self.front = (self.front+1) % self.size data = self.queue[self.front] self.queue[self.front] = 0 return data def isEmpty(self): return self.rear == self.front def isFull(self): return (self.rear+1) % self.size == self.front def showQueue(self): print(self.queue) if __name__ == '__main__': queue = circleQueue(5) #Testcase1:队列未插入任何值 print(queue.isEmpty()) #Expected:True print(queue.isFull()) #Expected:False # #Testcase2:队列空,出队列的值 # queue.deQueue() #Excepted:抛出队列空的异常 #Testcase3:队列未满,入队列和出队列 for i in range(1,4): queue.enQueue(i) queue.showQueue() #Expected:[0, 1, 2, 3, 0] print(queue.isEmpty()) #Expected:False print(queue.isFull()) #Expected:False queue.deQueue() queue.showQueue() #Expected:[0, 0, 2, 3, 0] # #Testcase4:队列已满,继续插入 # for i in range(1,5): # queue.enQueue(i) # queue.enQueue(5) #Expected:抛出队列满的异常
作者:LeechengLove



循环 队列 循环队列 Python 数组

需要 登录 后方可回复, 如果你还没有账号请 注册新账号