用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

用两个栈实现队列

http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

// 队列 先进先出 后进后出
// 栈 先进后出 后进先出
栈实现队列,push pop
// push方法向栈中添加元素,返回结果是当前添加的元素
// pop方法移除并返回栈顶元素,如果是空栈,会抛出异常:EmptyStackException
对队列 的push与对栈一样,向栈中添加元素
对队列 的pop应是移除并返回栈底元素,解决方法可将栈倒序,再对栈进行pop,再将栈倒序,则为队列正常顺序
双栈可实现上列倒序

public class Solution {
Stack<integer> stack1 = new Stack<integer>();
Stack<integer> stack2 = new Stack<integer>();</integer></integer></integer></integer>

public void push(int node) {
    int a = stack1.push(node);
    //return a;
}

public int pop() {
    while (stack1.size() != 0){
        int b = stack1.pop();
        stack2.push(b);
    } 
    int c = stack2.pop();
    while(stack2.size() != 0){
        int d = stack2.pop();
        stack1.push(d);
    }
    return c ;

}

}

全部评论
int b = stack1.pop(); 右边返回void, 如何赋值给int b?
点赞 回复 分享
发布于 2021-02-16 23:59

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务