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.
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.
You tried:
// yes, right, but set the 'next' of the current tail first, before you lose the reference.
// No, you dont need to do anything with the head when adding new nodes.