用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
栈是先进后出,队列是先进先出。
举例:将1,2,3,4,5入队
思路:先入栈1(顶-->底:5,4,3,2,1),再将栈1出栈的数据入栈到栈2(顶-->底:1,2,3,4,5),
这时栈2出栈的顺序就是先进先出了(1,2,3,4,5)
问题:当栈2还有元素时,栈1又入栈元素?
解决:每次栈2出栈后再检查栈2有没有元素,如果有,就把栈2的元素出栈,入栈到栈1.这样就把上次入队的还未出队的元素重新提前入队一次,接着再入队新数据
import java.util.Stack;
public class TwoStacksToList {
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) {
TwoStacksToList t = new TwoStacksToList();
t.push(1);
t.push(2);
t.push(3);
System.out.println(t.pop());
System.out.println(t.pop());
t.push(4);
t.push(5);
System.out.println(t.pop());
System.out.println(t.pop());
System.out.println(t.pop());
}
}