以下是使用Python编写的循环队列的入队和出队算法:

class CircularQueue:
    def __init__(self, capacity):
        self.capacity = capacity
        self.queue = [None] * capacity
        self.front = 0
        self.rear = 0
        self.flag = 0

    def enqueue(self, item):
        if self.front == self.rear and self.flag == 1:
            print('overflow')  # 队满
        else:
            self.queue[self.rear] = item
            self.rear = (self.rear + 1) % self.capacity
            if self.front == self.rear:
                self.flag = 1

    def dequeue(self):
        if self.front == self.rear and self.flag == 0:
            print('Empty')  # 队空
        else:
            item = self.queue[self.front]
            self.front = (self.front + 1) % self.capacity
            if self.front == self.rear:
                self.flag = 0
            return item


m = int(input())
inputs = list(map(int, input().split()))
n = int(input())

queue = CircularQueue(m + 1)
for i in range(m):
    queue.enqueue(inputs[i])

for i in range(n):
    queue.dequeue()

item = queue.dequeue()
if item is not None:
    print(item)

该算法首先定义了一个CircularQueue类,包含了队列的容量、队列数组、队首指针、队尾指针、标志位等属性。在入队操作中,如果队列已满,则输出'overflow';否则,在队尾插入元素,并更新队尾指针及标志位。在出队操作中,如果队列为空,则输出'Empty';否则,取出队首元素,并更新队首指针及标志位。最后,打印出队列中的元素。

输入说明

  • 入队次数m以及m个入队元素;(中间用空格隔开)
  • 出队次数n;

输出说明

  • 执行m次入队操作,如果队满输出'overflow';
  • 在执行n次出队操作后,打印队列中的元素:如果队列为空则输出'Empty'。

输入样例

3
5 3 6
2

输出样例

6
Python实现循环队列:入队、出队算法及标志位

原文地址: https://www.cveoy.top/t/topic/vfz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录