Niu Ke (5) Two stacks to implement a queue

// Implement a queue with two stacks to complete the Push and Pop operations of the queue. The elements in the queue are of type int. 

Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() {
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212596&siteId=291194637