java - 如何在java中添加到队列的开头
问题描述
我正在使用具有实例方法 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!
推荐阅读
- python - numpy数组索引:每行的不同列
- javascript - 如何基于普通对象创建嵌套数组
- amazon-web-services - 发生错误:ApiGatewayResourceUsers - 属性 ParentId 的值必须是字符串类型
- performance - 内存使用率高的 dotnet 进程过多
- docker - 是否可以使 docker 的容器输出着色?
- java - 尝试将图像上传到 Firebase 但失败
- hyperledger-fabric - 超级账本结构中私人集合中的差异链码(智能合约)
- kubernetes - 假设 iptables 代理问题,如何修复 kube-proxy 未知代理模式“”?
- cefsharp - 打印到 PDF 无法处理页眉和页脚设置
- declaration - 变量声明中的冒号有什么用?