[英]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.我正在尝试打印队列的值,但不知道为什么我会出错 output。 I have used java can you help me solving this?我用过 java 你能帮我解决这个问题吗? The output i'm getting is 7 7 But expected output is 7 5 8 6 7我得到的 output 是 7 7 但预计 output 是 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();
}
}
The expected output is 5 5 8 6 7 since print() outputs the front (=5) element.预期的 output 为 5 5 8 6 7,因为 print() 输出前 (=5) 元素。 It's rear element which contains 7. And for the output 5 5 8 6 7 you need this code:它是包含 7 的后部元素。对于 output 5 5 8 6 7,您需要以下代码:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.