I wrote the following implementation of the queue using a linked list that does not maintain a reference to the tail node. When I try to print the queue, it outputs only the head i.e. only one node. What is the error? Thanks in advance!
package DataStructures;
import java.util.Scanner;
class Node {
int x;
Node nextNode;
public Node(int x) {
this.x = x;
nextNode = null;
}
}
class Queue {
Node head = null;
int n = 0;
public void enqueue(int x) {
if (n==0){
head = new Node(x);
n++;
return;
}
Node tempHead = head;
while (tempHead != null){
tempHead = tempHead.nextNode;
}
tempHead = new Node(x);
tempHead.nextNode = null;
n++;
}
public int dequeue() {
if (head == null) {
throw new Error("Queue under flow Error!");
} else {
int x = head.x;
head = head.nextNode;
return x;
}
}
public void printTheQueue() {
Node tempNode = head;
System.out.println("hi");
while (tempNode != null){
System.out.print(tempNode.x + " ");
tempNode = tempNode.nextNode;
}
}
}
public class QueueTest {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
Queue queue = new Queue();
while (true){
int x = in.nextInt();
if (x == -1){
break;
} else{
queue.enqueue(x);
}
}
queue.printTheQueue();
}
}
headand your new node.