Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
package com.jianzhioffer;
import java.util.Stack;
public class TwoStacks {
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();
}
public static void main(String[] args) throws Exception{
TwoStacks s = new TwoStacks();
s.push(1);
s.push(2);
int n = s.pop();
System.out.println(n);
s.push(3);
n = s.pop();
System.out.println(n);
n = s.pop();
System.out.println(n);
s.push(4);
n = s.pop();
System.out.println(n);
}
}
Summary: The use of two stacks realize the function of a queue, very interesting, which requires advanced features that take full advantage of the stack. A first data push to the stack, then the B to A stack element pop the stack, the stack will be B A stack of such elements and a lower inverted.