代码随想录算法训练营第十天| 232. 用栈实现队列 225. 用队列实现栈

232. 用栈实现队列
https://leetcode.cn/problems/implement-queue-using-stacks/description/

class MyQueue {

    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    public void push(int x){
        stackIn.add(x);
    }
    public int pop(){
        dumpstackIn();
        return stackOut.pop();
    }
    public int peek(){
        dumpstackIn();
        return stackOut.peek();
    }
    public boolean empty(){
        return stackOut.isEmpty() && stackIn.isEmpty();
    }
    public void dumpstackIn(){
        if (stackOut.isEmpty()){
            while (!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
            }
        }
    }
}

总结:两个栈,栈顶放一起,栈顶向两边,重点就是out栈空了的时候从in栈拿元素放out栈里
225. 用队列实现栈
https://leetcode.cn/problems/implement-stack-using-queues/description/

Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }

    //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
    public void push(int x) {
        queue.offer(x);
        int size = queue.size();
        //移动除了 A 的其它数
        while (size-- > 1)
            queue.offer(queue.poll());
    }

    public int pop() {
        return queue.poll();
    }

    public int top() {
        return queue.peek();
    }

    public boolean empty() {
        return queue.isEmpty();
    }

总结:每次插入元素之后都让他去队首(把队列中的元素重新排列)

posted @   jeasonGo  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示