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

LintCode-40. 用栈实现队列

作者头像
悠扬前奏
发布2019-05-29 17:10:16
2570
发布2019-05-29 17:10:16
举报

描述

正如标题所述,你需要使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。

样例

例1:

代码语言:javascript
复制
输入:
    push(1)
    pop()    
    push(2)
    push(3)
    top()    
    pop()     
输出:
    1
    2
    2

例2:

代码语言:javascript
复制
输入:
    push(1)
    push(2)
    push(2)
    push(3)
    push(4)
    push(5)
    push(6)
    push(7)
    push(1)
输出:
[]

解答

思路

两个栈,一个负责入,一个负责出。每次入/出,都是吧一个栈的数据倒到另外一个栈里面在入/出。

代码

代码语言:javascript
复制
public class MyQueue {
    
    // 作为入队序列
    private Stack<Integer> s1 = new Stack<Integer>();
    // 作为出队序列
    private Stack<Integer> s2 = new Stack<Integer>();

    public MyQueue() {
        // do intialization if necessary
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
        while(!s2.empty()){
            s1.push(s2.pop());
        }
        s1.push(element);
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
        while(!s1.empty()){
            s2.push(s1.pop());
        }
        return s2.pop();
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        while(!s1.empty()){
            s2.push(s1.pop());
        }
        return s2.peek();
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.02.13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 描述
    • 样例
    • 解答
      • 思路
        • 代码
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档