gpt4 book ai didi

java - 如何在java中添加到队列的开头

转载 作者:行者123 更新时间:2023-12-01 17:31:48 26 4
gpt4 key购买 nike

我正在使用具有实例方法 setNext、getNext 的节点制作一个简单的队列实现。我正在编写的类具有 Node First 和 Node Last 字段。我的入队方法必须有3种情况

(1) 添加到列表末尾(普通队列实现)

this.back.setNext(node to add);
this.back = (node to add);

(2) 添加到空列表

this.front = this.back = (node to add);

(3) 添加到列表前面(从而将所有其他元素移回后面)

这对我来说似乎很简单,但我很难弄清楚如何使所有下一个值匹配并且不覆盖任何节点。请让我知道可以做到这一点的算法。谢谢!

更新:我尝试过的一种实现是使用数组:

Node[] x = new Node[this.totalNodes+1];
Node current = this.front;
int i = 0;
while(current != null) {
x[i] = current;
current = current.getNext();
i++;
}
int j = 0;
Node current2 = this.front;
this.front = (node to add)
while(j < x.length-1) {

current2.setNext(x[j+1]);
current2 = current2.getNext();
j++;
}

最佳答案

也许这就是你想要的

public class MyDS {
Node head=null;
Node next=null;
class Node
{
String data;
Node link=null;
Node(String s)
{
data=s;
}
}
public void add(Node n)
{
if(head == null)
{
head = n;
n.link = null;
}
else
{
if(next == null)
{
next = n;
head.link = next;
}
else
{
next.link = n;
next = n;

}
}

}
public void addTop(Node n)
{
if(head == null)
{
head = n;
n.link = null;
}
else
{
Node oldHead = head;
head = n;
n.link = oldHead;

}
}

public String print()
{
String str="";
Node startN=head;
while(startN.link != null)
{
str+=startN.data+"_";
startN = startN.link;
}
if(startN.data !=null) str+=startN.data+"_End!";
return str;
}

public static void main(String args[])
{
MyDS myDS = new MyDS();
myDS.add(myDS.new Node("a"));
myDS.add(myDS.new Node("b"));
myDS.add(myDS.new Node("c"));
myDS.addTop(myDS.new Node("d"));
myDS.add(myDS.new Node("e"));
myDS.addTop(myDS.new Node("f"));
System.out.println(myDS.print());
}
}


输出

f_d_a_b_c_e_End!

关于java - 如何在java中添加到队列的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61107980/

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