我正在为我的一个类创建一个项目,目标是使用堆栈创建一个队列。我想我已经有了该类(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();
}
}
我还使用以下类进行测试:
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());
}
}
运行程序后我收到此错误:
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)
我不确定如何继续解决此错误,因为当我对 pop() 方法中的 temp 变量进行错误测试时,它存储了正确的 int 5,但随后删除了该数字。
最佳答案
看起来在您的 pop()
方法中(也在 peek()
中),您成功地从 sQueue 中删除了第一个元素,但您从未推回tempStack 中的所有元素都放入 queue
堆栈中。因此,当您尝试弹出下一个元素时,您正在处理一个空的队列
。
关于java - 我的项目中的 pop() 方法出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623521/