Monday, July 19, 2021

LintCode 40 · Implement Queue by Two Stacks.java

public class MyQueue {
Stack<Integer> stack = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public MyQueue() {
// do intialization if necessary
stack = new Stack<>();
stack2 = new Stack<>();
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) {
// write your code here
stack.push(element);
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
if (stack2.isEmpty()) {
while (!stack.isEmpty()) {
stack2.push(stack.pop());
}
}
return stack2.pop();
}
/*
* @return: An integer
*/
public int top() {
// write your code here
if (stack2.isEmpty()) {
while (!stack.isEmpty()) {
stack2.push(stack.pop());
}
}
return stack2.peek();
}
}

No comments:

Post a Comment