Reputation: 590
I am learning the Queue Data structure.I want to create Queue with linked list.I want to program ouput : 10 20 Program output: Queue empty -1 Queue empty -1
Where am I making mistakes?
The code is as given below:
class Node {
int x;
Node next;
Node (int x){
this.x=x;
next=null;
}
}
public class QueQueLinked {
static Node root=null;
static Node latest=null;
public static void enque(int x){
if(root==null){
Node root=new Node(x);
root.x=x;
root.next=null;
latest=root;
}
else{
latest.next=new Node(x);
latest=latest.next;
latest.next=null;
}
}
public static int deque(){
if(root==null){
System.out.println("Queque empty");
return -1;
}
int value=root.x;
root=root.next;
return value;
}
public static void main(String[] args) {
enque(10);
enque(20);
System.out.println(deque());
System.out.println(deque());
}
}
Upvotes: 0
Views: 57
Reputation: 167
Your error is in this line:
Node root=new Node(x);
You are creating a new local variable named root
that hides the the static field root
. Instead you should write:
root=new Node(x);
If you have a local variable root
that hides the static field root
you could also access the static field by prepending it with your class name:
QueQueLinked.root = new Node(x)
In this case, however, you should rethink your variable names.
Upvotes: 2
Reputation: 23483
You are overwriting your root variable. You need to do:
public static void enque(int x){
if(root==null){
root=new Node(x);
root.x=x;
root.next=null;
latest=root;
}
Upvotes: 2