232. Implement Queue using Stacks
来源:互联网 发布:057188157858是淘宝网 编辑:程序博客网 时间:2024/06/03 10:01
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> mainStack; // Push element x to the back of queue. void push(int x) { mainStack.push(x); } // Removes the element from in front of queue. void pop(void) { stack<int> secondStack; while(!mainStack.empty()) { secondStack.push(mainStack.top()); mainStack.pop(); } secondStack.pop(); while(!secondStack.empty()) { mainStack.push(secondStack.top()); secondStack.pop(); } } // Get the front element. int peek(void) { stack<int> secondStack; while(!mainStack.empty()) { secondStack.push(mainStack.top()); mainStack.pop(); } int result = secondStack.top(); while(!secondStack.empty()) { mainStack.push(secondStack.top()); secondStack.pop(); } return result; } // Return whether the queue is empty. bool empty(void) { if(mainStack.empty()) { return true; } else { return false; } }};
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- jsp核心标签库(JSTL)
- AndroidStudio创建带有toolbar的模板
- STL基础
- 【记录】SMT32 USART发送接收
- elf文件格式与动态链接库
- 232. Implement Queue using Stacks
- 浅谈Python装饰器
- Android开发中结束所有Activity的方法
- 缓冲区溢出代码实例总结
- leetcode Divide Two Integers
- 初学Core data笔记
- ios中对字符的限制
- 2550: 记数问题
- WebSocket