我正在使用队列作为链接列表,将元素添加到列表的后面并将它们从前面删除。然而,我在添加新节点的概念上遇到了困难,因为我无法使用 FIFO 将预先存在的节点链接在一起。
你可以在这张图片下面看到我的方法。
public void add(Object data)
{
if data == null) throw new IllegalArgumentException() ;
Node newNode = new Node (data, null);
if (size == 0){ //- remember we are adding elements to the back
tail = newNode;
head = newNode;
}
else {
tail = newNode; //right
newNode.next = head.next; //??? What should be in place of this?
}
size++;
}
我正在按照图表进行操作,但不知道如何引用前一个节点。这是提供给该类的信息。
public class QueueNode
{
private Node head, tail ;
private int size ;
/**
inner class for Node
*/
private static class Node
{
Node next ;
Object data ;
public Node(Object data, Node n)
{
next = n ;
this.data = data ;
}
}
/**
Constructor for queue
*/
public QueueNode()
{
head = tail = null ;
size = 0 ;
}
//下课(不需要)
最佳答案
您只需设置当前尾部广告的下一个要添加的节点。新节点将成为尾部。
tail.next = newNode;
tail = newNode
您尝试过:
tail = newNode; //right
//是的,没错,但是在丢失引用之前先设置当前尾部的“下一个”。
newNode.next = head.next; //??? What should be in place of this?
//不,添加新节点时不需要对头部执行任何操作。
关于Java - 队列作为链接列表 - 将新节点添加到队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22444779/