Thanks for your help! The variables not being intialized and the null comparison were at fault. Now I seem to have a logic problem that I cannot wrap my head around. The problem appears to be in the push method. I push on 5 numbers 1, 2, 3, 4, 5 in that order so when I pop() them I should get 5, 4, 3, 2, 1 however I get this instead:
1
5
3
2
The stack is empty, nothing to return
0
Here is the code:
package com.shadowconcept.mcdougal;
import java.util.*;
public class StackImplementationUsingTwoQueues {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
}
else {
int pop = q1.remove();
return pop;
}
}
public void push(int data){
if (q1.peek() == null){
q1.add(data);
}
else {
for (int i = 0; i < q1.size(); i++){
q2.add(q1.remove());
}
q1.add(data);
for (int j = 0; j < q2.size(); j++){
q1.add(q2.remove());
}
}
}
public int top(){
if (q1.peek() == null){
int temp = 0;
System.out.println("The Stack is empty returning value 0");
return temp;
}
return q1.peek();
}
public int size(){
return q1.size();
}
public static void main(String[] args) {
StackImplementationUsingTwoQueues s1 = new StackImplementationUsingTwoQueues();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}