首页 > 解决方案 > 如何在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++;
    }

标签: javaqueue

解决方案


也许这就是你想要的

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!


推荐阅读