232.Implement Queue using Stacks(用栈实现队列)
来源:互联网 发布:linux系统怎么样 编辑:程序博客网 时间:2024/05/17 00:18
题目: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.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis 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 MyQueue {
// Push element x to the back of queue.
Stack <Integer> stack = new Stack();
Stack <Integer> tmp = new Stack();
public void push(int x) {
while(!stack.isEmpty()){
tmp.push(stack.pop());
}
stack.push(x);
while(!tmp.isEmpty()){
stack.push(tmp.pop());
}
}
// Removes the element from in front of queue.
public void pop() {
stack.pop();
}
// Get the front element.
public int peek() {
return stack.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stack.isEmpty();
}
}
// Push element x to the back of queue.
Stack <Integer> stack = new Stack();
Stack <Integer> tmp = new Stack();
public void push(int x) {
while(!stack.isEmpty()){
tmp.push(stack.pop());
}
stack.push(x);
while(!tmp.isEmpty()){
stack.push(tmp.pop());
}
}
// Removes the element from in front of queue.
public void pop() {
stack.pop();
}
// Get the front element.
public int peek() {
return stack.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stack.isEmpty();
}
}
0 0
- 232.Implement Queue using Stacks(用栈实现队列)
- 232. Implement Queue using Stacks (用栈实现队列)
- 队列-Implement Queue using Stacks(用栈实现队列)
- leetcode 232. Implement Queue using Stacks 双栈实现队列
- Implement Queue using Stacks(用栈实现队列)
- LeetCode 232. Implement Queue using Stacks(用栈实现队列)
- 232. Implement Queue using Stacks | 用栈实现队列的功能
- Implement Queue using Stacks 用俩栈实现队列
- Implement Queue using Stacks 两个栈实现队列
- Leetcode232. Implement Queue using Stacks[栈实现队列]
- LeetCode(23)-Implement Queue using Stacks(栈实现队列)
- LeetCode Implement Queue using Stacks 栈&队列
- leetcode 232. Implement Queue using Stacks-栈模拟队列
- leetcode:用两个栈实现一个队列 Implement Queue using Stacks
- 232. Implement Queue using Stacks (栈)
- 【LeetCode】 Implement Queue by Two Stacks用栈实现队列
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- Linux grep命令详解
- RSA算法原理
- 赶集网dba石展分享归纳
- SAP CRM RDS快速部署解决方案
- Android之GPS定位详解
- 232.Implement Queue using Stacks(用栈实现队列)
- oracle 外部表 如何忽略第一行的标题
- shrink-to-fit(自适应宽度)
- HDU 2019 数列有序!
- jQuery插件的开发
- Android开发笔记---不同activity之间的数据传递
- javascript数组循环遍历之foreach
- JAVA BASE64 加密解密实现代码
- mysql 数据库参数配置