简体   繁体   English

Java-队列作为LinkedLists-将新节点添加到队列

[英]Java - Queues as LinkedLists - Adding new nodes to the Queue

Im working with a Queue as a LinkedList adding elements to the back of the list and removing them from the front. 我将队列作为LinkedList使用,在列表的后面添加了元素,并从前面删除了元素。 However I am struggling with the concept of adding new nodes as I cant manage to link the pre-existing nodes together using FIFO. 但是,由于无法管理使用FIFO将先前存在的节点链接在一起,因此我在添加新节点的概念方面感到困惑。

You can see my method below this picture. 您可以在这张图片下面看到我的方法。

在此处输入图片说明

 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++;

    }

Im following the diagram but dont know how to reference the previous node .Here is the information given to the class. 我遵循该图,但不知道如何引用上一个节点。以下是提供给该类的信息。

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 ;
    }

//rest of class (not needed) //课程的其余部分(不需要)

You will only need to set the next of the current tail ad the node being added. 您只需要设置要添加节点的当前尾部广告中的下一个。 And the newnode will became the tail. 新节点将成为尾巴。

tail.next = newNode;
tail = newNode

You tried: 您尝试过:

tail = newNode; //right  

// yes, right, but set the 'next' of the current tail first, before you lose the reference. //是的,是的,但是在丢失参考之前,请先设置当前尾巴的“下一个”。

newNode.next = head.next; //??? What should be in place of this?

// No, you dont need to do anything with the head when adding new nodes. //不,添加新节点时不需要用头部做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM