gpt4 book ai didi

java - 像队列一样使用数组

转载 作者:行者123 更新时间:2023-12-01 10:09:39 25 4
gpt4 key购买 nike

我的队列类有问题。队列是基于数组的。当队列项到达数组末尾时,应将它们添加到数组开头。如果队列已满,则应删除并显示最旧的队列项目。当插入第 8 个元素时,我无法显示已删除的最旧项目。

当用户选择显示前 3 个客户的姓名时,代码应将它们从队列中一一删除(先进先出),并在删除时显示它们。

输入和输出示例:

队列输入是:A乙CdeFGh

队列输出是:H乙CdeF克

删除的项目是:h

预期输出应为:

H乙CdeFG删除的项目是:


因此它将最后插入的项目移动到数组的前面,但是我如何显示“项目已删除是:a”我的代码是:

public class MyQueue {

private final static int CAPACITY = 7;
static String qitems[] = new String[CAPACITY];
private static int front = 0, end = 0, count=0;

public void addqueue(String name) {
qitems[end] = name;
count++;
if(count==7) {
takequeue();
System.out.println("Queue is full");
}
end = (end + 1) % 7;
}

public void takequeue() {
System.out.println("Item removed:"+qitems[front]);
front = (front +1) % 7;
}

public void displayNames() {
System.out.println(" 3 names entered are: ");
for (int x = 0; x < 3; x++) {
System.out.println(qitems[x]);
}
}
}

最佳答案



public class QWithArray {

String[] qItems;
int front;
int end;
int current;

QWithArray(int CAPACITY) {
qItems = new String[CAPACITY];
current = 0;
front = -1;
end = -1;
}

public void addqueue(String element) {
if (current == qItems.length) {
System.out.println("Item removed was: " + qItems[(front + 1) % qItems.length]);
}

front = (front + 1) % qItems.length;
qItems[front] = element;
current++;

if (end == -1) {
end = front;
}
}

public String takequeue() {
if (current == 0) {
System.out.println("Queue is empty; can't remove.");
return null;
}

String result = qItems[end];
qItems[end] = null;

end = (end + 1) % qItems.length;
current--;

if (current == 0) {
front = -1;
end = -1;
}
return result;
}

public static void main(String[] args) {
QWithArray q = new QWithArray(7);
q.addqueue("a");
q.addqueue("b");
q.addqueue("c");
q.addqueue("d");
q.addqueue("e");
q.addqueue("f");
q.addqueue("g");
System.out.println(Arrays.toString(q.qItems));

q.addqueue("h");
System.out.println(Arrays.toString(q.qItems));
}
}

输出为:


[a, b, c, d, e, f, g]

Item removed was: a

[h, b, c, d, e, f, g]


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

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