0

Im working with a Queue as a LinkedList adding elements to the back of the list and removing them from the front. However I am struggling with the concept of adding new nodes as I cant manage to link the pre-existing nodes together using FIFO.

You can see my method below this picture.

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

    }

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)

3
  • Why do you need to reference the previous node? If you really do, then maybe a doubly linked list is what you need. Commented Mar 17, 2014 at 0:01
  • When I add a new node and make it the tail I don't know how to link it to the node above it. I thought head.next would work but it doesn't. Commented Mar 17, 2014 at 0:04
  • EDIT: I edited my code. Commented Mar 17, 2014 at 0:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.