gpt4 book ai didi

java - java中使用数组进行队列

转载 作者:行者123 更新时间:2023-12-02 06:16:17 27 4
gpt4 key购买 nike

我只想在队列中询问,例如我的队列中是否已经有 5 个元素,并且它的限制是 5。然后,我删除一个元素。然后我插入一个元素。是不是输出会溢出呢?我的问题是即使从队列中插入了新元素。总是说溢出。我想要的是在我的队列中添加更多元素。(我指的是上面的情况)

import java.io.*;  
import java.lang.*;
class clrqueue
{
DataInputStream get=new DataInputStream(System.in);
int a[];
int i,front=0,rear=0,n,item,count=0;
void getdata()
{
try
{
// to enter the limit

System.out.println("Enter the limit");
n=Integer.parseInt(get.readLine());
a=new int[n];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void enqueue()
{
try
{
if(count<n)
{
System.out.println("Enter the element to be added:");
item=Integer.parseInt(get.readLine());
a[rear]=item;
rear++;
count++;
}
else
System.out.println("QUEUE IS FULL");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}


void dequeue()
{
if(count!=0)
{
System.out.println("The item deleted is:"+a[front]);
front++;
count--;
}
else
System.out.println("QUEUE IS EMPTY");
if(rear==n)
rear=0;
}
void display()
{
int m=0;
if(count==0)
System.out.println("QUEUE IS EMPTY");
else
{
for(i=front;m<count;i++,m++)
System.out.println(" "+a[i]);
}
}
}
class Myqueue
{
public static void main(String arg[])
{
DataInputStream get=new DataInputStream(System.in);
int ch;
clrqueue obj=new clrqueue();
obj.getdata();
try
{
do
{
System.out.println(" 1.Enqueue 2.Dequeue 3.Display 4.Exit");
System.out.println("Enter the choice");
ch=Integer.parseInt(get.readLine());
switch (ch)
{
case 1:
obj.enqueue();
break;
case 2:
obj.dequeue();
break;
case 3:
obj.display();
break;
}
}
while(ch!=4);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

最佳答案

您想要实现一个循环队列。重点是,请小心保持前后指针,否则您会收到溢出或完整消息。请注意,当你执行front++、rear++时,你可以将它们设置为n,如果需要的话,每次执行mod n将有助于将其恢复为0。

front++;front%=n;

rear++;rear%=n;

for(i=front;m<count;i++,i%=n,m++)

您的实现几乎是正确的,继续。

关于java - java中使用数组进行队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21436378/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com