Python实现循环队列

循环队列的基本模型

完整Python代码

点击查看代码
#! /usr/bin/env python3


class Queue:
    # Implement Circualr Queue
    def __init__(self, maxsize):
        self.data = [0 for i in range(maxsize)]
        self.front = 0
        self.rear = 0
        self.maxsize = maxsize

    def is_empty(self):
        return self.rear == self.front

    def is_full(self):
        return (self.rear + 1) % self.maxsize == self.front

    def enqueue(self, element):
        if self.is_full():
            print("The queue is full!!!")
            return False
        else:
            self.rear = (self.rear + 1) % self.maxsize
            self.data[self.rear] = element

    def dequeue(self):
        if self.is_empty():
            print("Ths queue is empty!!!")
            return 99999
        else:
            self.front = (self.front + 1) % self.maxsize
            return self.data[self.front]


def main():
    queue = Queue(int(input("input maxsize: ")))
    while True:
        message = input("in/out/exit: ")
        if message == 'exit':
            break
        elif message == 'in':
            queue.enqueue(int(input("Enqueued Value: ")))
        elif message == 'out':
            print("Dequeued Value:", queue.dequeue())
        else:
            print("Please input in, out or exit")

        print("front={0:}, rear={1:}".format(queue.front, queue.rear))


if __name__ == '__main__':
    main()

程序执行结果

posted @ 2023-11-13 18:50  Guanjie255  阅读(46)  评论(0编辑  收藏  举报