Reputation: 4561
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)
Upvotes: 0
Views: 2266
Reputation: 2404
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.
Upvotes: 1