Implement Stack using Queues
来源:互联网 发布:星际淘宝网笔下 编辑:程序博客网 时间:2024/06/07 06:39
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.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis 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.
思路:用两个queue,q1, q2, q1用来装,然后当要pop的时候,把q1里面所有元素,except最后一个,全部放到q2里面,然后pop最后一个,然后q1,q2交换顺序。所有的费时操作都在pop和top中。
class MyStack { Queue<Integer> queue1 = new LinkedList<Integer>(); Queue<Integer> queue2 = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { queue1.add(x); } // Removes the element on top of the stack. public void pop() { if(queue1.size()!=0){ while(queue1.size()>1){ queue2.add(queue1.poll()); } queue1.poll(); Queue<Integer> temp = queue1; queue1 = queue2; queue2 = temp; } } // Get the top element. public int top() { while(queue1.size()>1){ queue2.add(queue1.poll()); } return queue1.peek(); } // Return whether the stack is empty. public boolean empty() { return (queue1.size()+queue2.size()) == 0; }}
0 0
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Spring集成Shiro HelloWorld之初步实现登陆及验证
- hadoop机架感知
- LeetCode--No.20--Valid Parentheses
- 机器学习这么火,想跳坑该怎么做?
- 陶哲轩实分析-第18章 Lebesgue积分
- Implement Stack using Queues
- 【日志7.13】
- Meta http-equiv属性详解
- LeetCode--No.38--Count and Say
- LeetCode--No.58--Length of Last Word
- 网络爬虫项目开发日志(一):关于爬虫项目所涉及的领域知识
- Design Pattern - Structural Patterns - Facade Pattern
- COCI2009 着色
- C# 关键字(Static/Const/Readonly)