Reputation: 497
I am trying to write my own queue class. My enqueue method is only enqueue-ing one object and then if I try to enqueue anything else, its almost as if its ignoring it. Here is my code:
public class myQueue {
private Node front;
private Node back;
private int s;
public myQueue() {
front = null;
back = null;
s = 0;
}
public void enqueue(Object x) {
if( isEmpty() )
back = front = new Node(x);
else
back = back.next = new Node(x);
s++;
}
public Object dequeue() {
Object x;
if( isEmpty() ) { System.out.println("nothing to dequeue.\nqueue empty."); }
x = front.data;
s--;
return x;
}
public boolean isEmpty() {
if(s == 0)
return true;
else
return false;
}
public void printQueue() {
if ( isEmpty() )
System.out.println("empty queue");
else {
Node temp = back;
while(temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
}
and here is my main method where i try to enqueue some objects:
public static void main(String[] args) {
int a = 5;
String b = "yo";
Object c = 5.5;
int d = 2;
String e = "Pen";
Object f = 9.2;
myQueue q = new myQueue();
q.enqueue(a);
q.enqueue(b);
q.enqueue(c);
q.enqueue(d);
q.enqueue(e);
q.enqueue(f);
System.out.println("\n");
q.printQueue();
}
and then all i get for output is:
data: 9.2
any ideas as to why this is happening?
Upvotes: 2
Views: 10196
Reputation: 15523
When you print, you are starting at the back of the queue, you should start at the front:
Node temp = front; // <<< replacing back by front
while(temp != null) {
System.out.println(temp);
temp = temp.next;
}
If you start at the back of the queue, you will only have the last element of the queue to be printed...
My result with the fix:
data : 5
data : yo
data : 5.5
data : 2
data : Pen
data : 9.2
Upvotes: 2