Implement Queue by Two Stack
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) {
stack1.push(element);
}
/*
* @return: An integer
*/
private void stack1Tostack2(){
while(!stack1.empty()){
stack2.push(stack1.peek());
stack1.pop();
}
}
public int pop() {
// write your code here
if(stack2.empty()){
stack1Tostack2();
}
return stack2.pop();
}
/*
* @return: An integer
*/
public int top() {
// write your code here
if(stack2.empty()){
stack1Tostack2();
}
return stack2.peek();
}
}
最后更新于
这有帮助吗?