Implement Stack using Queues

来源:互联网 发布:淘宝直播自我介绍词 编辑:程序博客网 时间:2024/05/14 10:43

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

Show Tags
Show Similar Problems

Have you met this question in a real interview?

思路: Every time after we add a new element, we need to pop all element and move them to tail.


class MyStack {    Queue<Integer> q = new LinkedList<Integer>();    // Push element x onto stack.    public void push(int x) {        q.add(x);        int n = q.size();        while(n > 1){            q.add(q.poll());            n--;        }    }    // Removes the element on top of the stack.    public void pop() {        q.poll();    }    // Get the top element.    public int top() {        return q.peek();    }    // Return whether the stack is empty.    public boolean empty() {        return q.isEmpty();    }}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 头皮上白色像癣怎么办 脸上长了火疖子怎么办 脸上长硬硬的包怎么办 下身体痒痒得不得了怎么办 头皮干痒头屑多怎么办 头发掉的露头皮怎么办 头上老是有结痂怎么办 婴儿头上的黄痂怎么办 头皮屑多又痒怎么办小偏方 皮肤瘙痒起红疙瘩怎么办 头又油又痒怎么办 头上反复长脓包怎么办 额头上长了粉刺怎么办 身上长红疙瘩很痒怎么办 脸上的痘痘变硬怎么办 痘痘变成硬疙瘩怎么办 痘痘变硬了怎么办知乎 痘痘里面是硬的怎么办 皮肤出油毛孔大怎么办 蹭无线网信号差怎么办 无线网离得太远怎么办 无线网不好使了怎么办 火疖子化脓破了怎么办 脸上长了个疖子怎么办 脸上起了火疖子怎么办 脸上长了火疙瘩怎么办 脸上长疖子了该怎么办? 头上神经线疼怎么办 打了肉毒发烧了怎么办 不小心吃了活蛆怎么办 吃了生蛆的东西怎么办 我的世界中毒了怎么办 如果人染了尸气怎么办 汽车没油了怎么办紧急 不小心吃氧化钾怎么办 看3d电影没眼镜怎么办 wps宏被禁用了怎么办 京东三天不发货怎么办 京东商家不退款怎么办 苹果保修卡丢了怎么办 手机保修卡丢了怎么办