前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法-栈stack-用栈实现队列-Leetcode232

算法-栈stack-用栈实现队列-Leetcode232

作者头像
潇洒
发布2020-12-17 10:15:20
2750
发布2020-12-17 10:15:20
举报
文章被收录于专栏:石头岛石头岛石头岛

用栈实现队列

这个是 Leetcode 232 题,用两个栈来实现一个先进先出的队列,实现了一个版本。

https://leetcode-cn.com/problems/implement-queue-using-stacks/

class MyQueue {

    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    /**
     * Initialize your data structure here.
     */
    public MyQueue() {

    }

    /**
     * Push element x to the back of queue.
     */
    public void push(int x) {
        stack1.push(x);
    }

    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        int result = stack2.pop();
        while (!stack2.empty()) {
            stack1.push(stack2.pop());
        }
        return result;
    }

    /**
     * Get the front element.
     */
    public int peek() {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        int result = stack2.peek();
        while (!stack2.empty()) {
            stack1.push(stack2.pop());
        }
        return result;
    }

    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        return stack1.empty();
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-12-152,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用栈实现队列
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档