'Display all elements of queue using linked list

I am trying to print the values of Queue but don't know why I'm getting wrong output. I have used java Can you help me solving this?

The output I'm getting is 7 7 But expected output is 7 5 8 6 7

public class Main {
    
    public static class Node {
        public static int data;
        public static Node next;
    }

    public static Node rear = null;
    public static Node front = null;

    public static void enqueue(int data) {
        Node temp = new Node();
        temp.data = data;
        temp.next = null;
        if (rear == null) {
            front = temp;
            rear = temp;
        } else {
            rear.next = temp;
            rear = temp;
        }
    }

    public static void print() {
        System.out.println(front.data);
    }

    public static void printall() {
        Node dummy = front;
        while (dummy != rear) {
            System.out.println(dummy.data);
            dummy = dummy.next;
        }
    }

    public static void main(String[] args) {
        enqueue(5);
        enqueue(8);
        enqueue(6);
        enqueue(7);
        print();
        printall();
    }
}


Solution 1:[1]

The expected output is 5 5 8 6 7 since print() outputs the front (=5) element. It's rear element which contains 7. And for the output 5 5 8 6 7 you need this code:

public class Main {

    public static class Node {
        public int data;
        public Node next;
    }

    public static Node rear = null;
    public static Node front = null;

    public static void enqueue(int data) {
        Node temp = new Node();
        temp.data = data;
        temp.next = null;
        if (rear == null) {
            front = temp;
        } else {
            rear.next = temp;
        }
        rear = temp;
    }
    public static void print() {
        System.out.println(front.data);
    }
    public static void printall() {
        Node dummy = front;
        // the first element to be handled in a specific way
        if (dummy != null) {
            System.out.println(dummy.data);
        }
        // while will handle elements after the first one
        while (dummy.next != null) {
            System.out.println(dummy.next.data);
            dummy = dummy.next;
        }
    }

    public static void main(String[] args) {
        enqueue(5);
        enqueue(8);
        enqueue(6);
        enqueue(7);
        print();
        printall();
    }
} 

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 dimirsen Z