简体   繁体   English

使用python实现队列

[英]Queue implementation using python

I'm creating a program to create a queue and add,delete and display elements.我正在创建一个程序来创建一个队列并添加、删除和显示元素。 For this I create a list, then take input from users and append the same number of 0s and then proceed normally.为此,我创建了一个列表,然后从用户那里获取输入并附加相同数量的 0,然后正常进行。 The problem arises that the value of rear and front does not change and remains constant which leads to it not displaying and also not filling up.出现的问题是后部和前部的值没有改变并保持不变,导致它不显示也不填满。

How can I fix this.我怎样才能解决这个问题。

l=[]
global front
global rear
front=-1
rear=-1
print("Enter the number of elements ")
maxsize=int(input())
i=0
q=0
for q in range(0,maxsize):       #for creating an array with user input number of 0s
    l.append(0)

def isFull():
    if(rear==maxsize):
        return 1
    else:
        return 0

def isEmpty():
    if(front==-1 and rear==-1):
        return 1
    elif(front==rear):
        return 1
    else:
        return 0

def enqueue(n):
    if(isEmpty()==1):
        front=0
        rear=0
        l[rear]=n
        rear=rear+1
    else:
        l[rear]=n
        rear=rear+1

def dequeue():
    if(isEmpty()==1):
        return 1
    else:
        front=front+1

while(i==0):
    print("Add an element ?(0) \nDelete an element?(1) \nDisplay the 
elements?(2)\n")
    a=int(input())
    if(a==0):
        if(isFull()==1):
            print("Queue is full")
        else:
            b=int(input())
            enqueue(b)
    if(a==1):
        dequeue()
    if(a==2):
        for c in range(front,rear):
            print(l[c])

You have to redeclare the global variables (front,rear in this case) at the start of any methods using them.您必须在使用它们的任何方法开始时重新声明全局变量(在本例中为 front,rear)。 Like this像这样

def enqueue(n):
    global front
    global rear
    if(isEmpty()==1):
        front=0
        rear=0
        l[rear]=n
        rear=rear+1
    else:
        l[rear]=n
        rear=rear+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM