题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
把数据push到A栈中,然后pop到B栈中,这时B栈中的数据和之前A栈中的数据时相反的,这是pop的数据就实现了先进先出,然后再把B栈中的数据pop出来存入A栈中,这时A中的数据仍是pop最先存入的数据后其他的存储数据。
import java.util.Stack;
public class QueueImplmentByStatck {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int first = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return first;
}
public static void main(String[] args) {
QueueImplmentByStatck queueImplmentByStatck = new QueueImplmentByStatck();
queueImplmentByStatck.push(1);
queueImplmentByStatck.push(2);
queueImplmentByStatck.push(3);
queueImplmentByStatck.push(4);
System.out.println(queueImplmentByStatck.pop());
System.out.println(queueImplmentByStatck.pop());
queueImplmentByStatck.push(5);
System.out.println(queueImplmentByStatck.pop());
}
}