40 - 用栈实现队列
程序员文章站
2022-07-15 12:14:41
...
2017.9.19
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
// do intialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) {
// write your code here
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(element);
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int x = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return x;
}
/*
* @return: An integer
*/
public int top() {
// write your code here
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int x = stack2.peek();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return x;
}
}
上一篇: 领扣LintCode算法问题答案-277. 单词间距
下一篇: lintcode