题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
栈的特点是先进后出,队列的特点是先进先出,使用stack1、stack2两个栈结构来实现一个队列,stack1主要用来进队,stack2用来出队,进队时无需改变,出队时只需每次都将stack1中的数据传入stack2即可。
Java版代码:
import java.util.Stack;
public class Solution {
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() ;
}
}