简体   繁体   中英

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();
    }
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM