牛客网刷题-用两个栈实现队列

问题描述

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

示例

示例1

push:1,2,3
pop:3,2,1

解决思路

分析

  1. 因为栈跟队列出入的顺序是相反的,所以我们可以借助两个栈解决问题,stack1负责存储push的数据,stack2负责在pop操作的时候,将statk1的输入依次压入stack2,这样出栈的顺序就变成了出队列的顺序。

代码实现

// 思路1
public class Solution {
    
      
    // 用两个栈来实现一个队列
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
    
    
        stack1.push(node);
    }

    public int pop() {
    
    
        while (stack2.isEmpty()) {
    
    
            while (!stack1.isEmpty()) {
    
    
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

小伙伴如果想测试的话,可以直接到牛客网这个链接做测试

用两个栈实现队列-牛客网

猜你喜欢

转载自blog.csdn.net/qq_35398517/article/details/113919455