232. Implement Queue using Stacks
2016-02-13 00:16
316 查看
class MyQueue {
// Push element x to the back of queue.
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(!s2.isEmpty())s2.pop();
else{
while(!s1.isEmpty()){
s2.push(s1.pop());
}
s2.pop();
}
/* if(!s2.isEmpty()) s2.pop();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
s2.pop();
}*/
}
// Get the front element.
public int peek() {
if(!s2.isEmpty()) return s2.peek();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
return s2.peek();
}
}
// Return whether the queue is empty.
public boolean empty() {
return s1.empty() && s2.empty();
}
}
// Push element x to the back of queue.
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(!s2.isEmpty())s2.pop();
else{
while(!s1.isEmpty()){
s2.push(s1.pop());
}
s2.pop();
}
/* if(!s2.isEmpty()) s2.pop();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
s2.pop();
}*/
}
// Get the front element.
public int peek() {
if(!s2.isEmpty()) return s2.peek();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
return s2.peek();
}
}
// Return whether the queue is empty.
public boolean empty() {
return s1.empty() && s2.empty();
}
}
相关文章推荐
- fluentd收集mapreduce分布式环境下的用户日志
- Codeforces Round #287 (Div. 2) C. Guess Your Way Out!(线段树思想)
- Arduino代码机制-avr/pgmspace.h
- 【HDOJ】4343 Interval query
- std::queue
- UITableView添加footerView按钮
- hdu 5297 Y sequence
- 不允许使用邮箱名称。 服务器响应为:authentication is required
- HRBUST 1005 Counting Subsequences
- POJ 2785 4 Values whose Sum is 0(折半枚举)
- Android蓝牙技术Bluetooth使用流程(详解)
- poj 3368 Frequent values 线段树 离散化
- Android蓝牙技术Bluetooth初体验
- String ,StringBuilder, StringBuffer
- SWTableViewCell——一个和iOS 7的系统Mail类似,使用起来简单的UITableViewCell子类
- UESTC 250 windy数 (数位DP)
- iOS 【UIKit-转换坐标系(2)】
- NGUI 3.5教程(二)Label 标签 (Hello world)、多行文本
- [JSP] - frequently-used skills
- Key-Value Coding