Reputation: 37
Im creating a project for one of my classes and the objective is to create a queue using a stack. I think I have the general framework for the class:
import java.util.LinkedList;
import java.util.Stack;
public class SQueue {
private Stack<Integer> queue;
public SQueue(Stack<Integer> inputQueue) {
queue = inputQueue;
}
public void push(int x) {
Stack<Integer> tempStack = new Stack<Integer>();
Stack<Integer> backwardsStack = new Stack<Integer>();
tempStack.push(x);
while(!queue.isEmpty()) {
backwardsStack.push(queue.pop());
}
while(!backwardsStack.isEmpty()) {
tempStack.push(backwardsStack.pop());
}
queue = tempStack;
}
public int pop() {
Stack<Integer> tempStack = new Stack<Integer>();
while(!queue.isEmpty()) {
tempStack.push(queue.pop());
}
int temp = tempStack.peek();
tempStack.pop();
return temp;
}
public int peek() {
Stack<Integer> tempStack = new Stack<Integer>();
while(!queue.isEmpty()) {
tempStack.push(queue.pop());
}
int temp = tempStack.peek();
return temp;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
Im also using the following class for testing:
import java.util.Stack;
public class SQueueTest {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
SQueue test1 = new SQueue(s);
SQueue test2 = new SQueue(s);
SQueue test3 = new SQueue(s);
case1(test1);
case2(test2);
case3(test3);
}
public static void case1(SQueue test) {
for(int i =1; i <6; i++) {
test.push(i);
}
for(int i =0; i <3; i++) {
test.pop();
}
System.out.println(test.peek());
}
public static void case2(SQueue test) {
test.push(2);
test.push(4);
test.push(8);
for(int i =0; i <2; i++) {
test.pop();
}
System.out.println(test.isEmpty());
}
public static void case3(SQueue test) {
for(int i = 1; i<4; i++) {
test.push(i*3);
}
test.pop();
System.out.println(test.peek());
System.out.println(test.isEmpty());
}
}
After running the program I received this error :
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at SQueue.pop(SQueue.java:27)
at SQueueTest.case1(SQueueTest.java:19)
at SQueueTest.main(SQueueTest.java:10)
Im not sure how to proceed with solving this error because while I was bug testing the temp variable in the pop() method stored the right int, 5, but then removed that digit.
Upvotes: 0
Views: 123
Reputation: 165
It looks like in your pop()
method (also in peek()
), you are successfully removing the first element from your sQueue, but you never push back all of the elements from your tempStack into your queue
stack. So you are dealing with an empty queue
when you try to pop off the next element.
Upvotes: 1