gpt4 book ai didi

java - 无法在 Java 中基于链表的队列中添加项目

转载 作者:行者123 更新时间:2023-11-30 08:41:40 26 4
gpt4 key购买 nike

我正在使用 Queue 和 LinkedList。因此,我按照一些教程创建了一个基于 LinkedList 的队列,并运行一个循环从 0 - 9 遍历以添加到这些数字。但是,完成后我发现文件开头有 10 个零,而不仅仅是 1。我从头部轮询了 1 个零并再次打印,但是现在,我有 10 个或更多的 1,而不是少了一个零( 0).这是我第一次使用队列,所以可能会有一些错误!我的代码如下:

    import java.util.LinkedList;
import java.util.Queue;

Queue<Integer> queue = new LinkedList<Integer>();

for(int i = 0; i < 10; i++)
{
System.out.println(i);
queue.add(i);
}

for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " >> ");
}
System.out.println();

System.out.println(queue.poll());
for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " $$ ");
}
System.out.println();


}}

这是我得到的输出集

0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 
0
1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$

据我所知,第一行应该有 0 >> 1 >> 2 >> 3.... 而不是只有零 (0)。并且后续的最后一行也不应该只有 1。 我被困在这里

最佳答案

您的代码实际上没问题。阅读Java documentation on Queues , 你会注意到 peek()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

多次调用 peek 不会更改您的队列。但是,如果你想删除元素,你可以使用 poll()

Retrieve and remove the head of this queue, or return null if this queue is empty.

关于java - 无法在 Java 中基于链表的队列中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34964791/

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