100. Implement Queue using Stacks
2016-05-27 22:29
555 查看
-232. Implement Queue using Stacks My Submissions QuestionEditorial Solution
Total Accepted: 44621 Total Submissions: 130935 Difficulty: Easy
Implement the following operations of a queue using stacks.
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
用栈实现队列:
老题-简单:自己看着实现
Total Accepted: 44621 Total Submissions: 130935 Difficulty: Easy
Implement the following operations of a queue using stacks.
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
用栈实现队列:
老题-简单:自己看着实现
class Queue { public: stack<int> s1,s2; // Push element x to the back of queue. void push(int x) { s1.push(x); } // Removes the element from in front of queue. void pop(void) { if(!s2.empty()){ s2.pop(); } else{ while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } if(!s2.empty())s2.pop(); } } // Get the front element. int peek(void) { if(!s2.empty())return s2.top(); else{ while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } return s2.top(); } } // Return whether the queue is empty. bool empty(void) { return s1.empty()&&s2.empty(); } };
相关文章推荐
- C#中using指令的几种用法
- C#队列Queue用法实例分析
- 谈C# using的用法与好处
- Locate a File Using a File Open Dialog Box
- Save a File Using a File Save Dialog Box
- 用PHP写的基于Memcache的Queue实现代码
- 找不到类型或命名空间名称“Server”(是否缺少 using 指令或程序集引用?)
- C#队列Queue多线程用法实例
- Mysql Error Code : 1436 Thread stack overrun
- linux中编写自己的并发队列类(Queue 并发阻塞队列)
- 基于java中stack与heap的区别,java中的垃圾回收机制的相关介绍
- vector,map,list,queue的区别详细解析
- Laravel 4.2 中队列服务(queue)使用感受
- Using the TextRange Object
- jQuery中队列queue()函数的实例教程
- Python Queue模块详解
- Python多进程通信Queue、Pipe、Value、Array实例
- python使用Queue在多个子进程间交换数据的方法
- Python算法之栈(stack)的实现
- HAZELCAST 客户端命令 可用于简单调试