leetcode232:栈实现队列

栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false
java 复制代码
class MyQueue {
        Stack<Integer> stack = new Stack<>();

        Stack<Integer> tmp = new Stack<>();

        public MyQueue() {

        }

        public void push(int x) {
            stack.push(x);
        }

        public int pop() {
            tmp.empty();
            while(!stack.empty()){
                tmp.push(stack.peek());
                stack.pop();
            }
            Integer res = tmp.pop();
            while(!tmp.empty()){
                stack.push(tmp.peek());
                tmp.pop();
            }
            return res;
        }

        public int peek() {
            tmp.empty();
            while(!stack.empty()){
                tmp.push(stack.peek());
                stack.pop();
            }
            Integer res = tmp.peek();
            while(!tmp.empty()){
                stack.push(tmp.peek());
                tmp.pop();
            }
            return res;
        }

        public boolean empty() {
            return stack.empty();
        }
    }

用另一个栈实现

相关推荐
爱coding的橙子8 分钟前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光10 分钟前
leetcode sql50题
算法·leetcode·职场和发展
pay顿11 分钟前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm12 分钟前
leetcode78. 子集
算法·深度优先
岁忧13 分钟前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy14 分钟前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
dying_man16 分钟前
LeetCode--18.四数之和
算法·leetcode
知识漫步42 分钟前
代码随想录算法训练营第60期第五十九天打卡
算法
分形数据1 小时前
在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)
算法·mathematica·复分析
鑫鑫向栄1 小时前
[蓝桥杯]解谜游戏
数据结构·c++·算法·职场和发展·蓝桥杯