Java - 队列作为链接​​列表 - 将新节点添加到队列

标签 java linked-list queue

我正在使用队列作为链接​​列表,将元素添加到列表的后面并将它们从前面删除。然而,我在添加新节点的概念上遇到了困难,因为我无法使用 FIFO 将预先存在的节点链接在一起。

你可以在这张图片下面看到我的方法。

enter image description here

 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/

相关文章:

java - 计算机突然重启后 Eclipse 4.7.2 不显示项目

java - Intellij IDEA 12.1.6 - hibernate 不解析表名或列名

java - 什么是在任何位置追加、前置和检索元素的 O(1) 复杂度的数据结构?

c - c中的迭代目录遍历

java - 如果没有在代码中修改,我应该声明一个 java 字段 'final' 吗?

java - 有哪些方法可以使 hashCode/equals 与类的业务定义保持一致?

C链表 "redefinition of structure"

c++ - 理解为什么存储在链表中的字符串不能正确打印

java - JMS 队列是 Java Util 队列的实现吗? Java 包中使用 Java Util Queue 实现的类有哪些?

javascript - 队列函数调用