java - 我的项目中的 pop() 方法出错

标签 java stack queue

我正在为我的一个类创建一个项目,目标是使用堆栈创建一个队列。我想我已经有了该类(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/

相关文章:

java - 无法从 WSDL 创建 JAX-WS 服务

python - 在 Python 中使用堆栈计算中缀表达式 : I cant find my error

f# - 如何在 F# 中使我的队列线程安全(并发)

java - 部署后的 WAR 版本

Java:System.out.println方法在打印字节数组时丢失了一些行

在堆栈顶部推送任何超过 127 的数字后,代码将停止工作

java - 从两个单独的线程并行访问队列

java - 在后台线程中运行的可编辑任务队列

java - 使用 JDK1.6.45 在 Windows 上进行 MongoDB 3.0.0/2/3 Java 驱动程序 Kerberos 身份验证

java - 多键、链接哈希