题解 | #【模板】循环队列#

【模板】循环队列

https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf?tpId=308&tqId=2372963&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308

import sys

# for line in sys.stdin:
#    a = line.split()
#   print(int(a[0]) + int(a[1]))


class CirculateQueue():
    def __init__(self,k:int):
        """
        设置队列的长度为k,初始化队列长度
        """
        self.L=[0] *k
        self.length = k
        self.count = 0
        self.tail= -1
        self.head= 0



    def push(self,x:int)->bool:
        """
        向环形队列中插入一个元素,如果插入成功返回True
        """
        if self.isFull() == False:
            if self.tail == self.length-1:
                self.tail =0
            else:
                self.tail +=1
            self.count+=1
            self.L[self.tail]=x
            return True
        else:
            return False

    def pop(self):
        """
        删除一个元素从环形队列中,如果操作成功,返回True
        """
        if self.isEmpty() ==False:
            print(self.L[self.head])
            self.L[self.head]=0
            self.count-=1
            if self.head !=self.tail:
                if self.head ==self.length -1:
                    self.head=0
                else:
                    self.head+=1


            else:
                self.head=0
                self.tail=-1
            return True
        else:
            return False



    def isEmpty(self)->bool:
        """
        判断对列是否为空环形队列
        """
        if self.count ==0:
            print("empty")
            return True
        else:
            return False






    def front(self):
        """
        返回环形队列的对首,不删除对首
        """
        if self.isEmpty():
            return -1
        else:
            print(self.L[self.head])
            return self.L[self.head]




    def isFull(self)->bool:
        """
        判断对列是否已经满了
        """
        if self.count == self.length:
            print("full")
            return True
        
        else:
            return False




L= input().split()
l,n=int(L[0]),int(L[1])
opration = []
Queue = CirculateQueue(l)
while n > 0:
    s = input()
    opration.append(s)
    n -= 1
for x in opration:
    if x[0:4] == "push":
        number = int(x[4:])
        Queue.push(number)

    if x == "pop":
        try:
            Queue.pop()
        except:
            print("error")

    if x == "front":
        try:
            Queue.front()
        except:
            print("error")

全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 18:14
RT,这周五就是情人节了,前女友给我发了消息,我该不该回?
Yoswell:原则上来说让她滚,但是本着工作很累下班想吃瓜的心态,我觉得你可以回一下
点赞 评论 收藏
分享
01-07 07:54
已编辑
门头沟学院 前端工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务