'Circular queue, how to print values using java
How to print values of circular queue using java Im getting output as null and expected output is 5,4,3,2,1. PLease help me. I'm don't know what is wrong.
public class Main
{
public static class Node{
public static int data;
public static Node next;
}
public static Node front = null, rear = null;
public static void enqueue(int data){
Node temp = new Node();
temp.data = data;
if(front == null){
front = temp;
}
else{
rear.next = temp;
}
rear = temp;
rear.next = front;
}
public static void displayQueue(){
Node temp = front;
while (temp.next != front) {
System.out.println(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
enqueue(5);
enqueue(4);
enqueue(3);
enqueue(2);
enqueue(1);
displayQueue();
}
}
Solution 1:[1]
You should study how static works... when you make something static it only has one value, so basically you are just modifying always the same value.
You also don't show all the values, you forget to show one in the loop, so the only value you have you dont show :(
Try this code, solves most of your problem
public class Main{
public static class Node{
public int data;
public Node next;
}
public static Node front = null, rear = null;
public static void enqueue(int data){
Node temp = new Node();
temp.data = data;
if(front == null){
front = temp;
}
else{
rear.next = temp;
}
rear = temp;
rear.next = front;
}
public static void displayQueue(){
Node temp = front;
while (temp.next != front) {
System.out.println(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
enqueue(5);
enqueue(4);
enqueue(3);
enqueue(2);
enqueue(1);
displayQueue();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raul Lapeira Herrero |
