1. push(),stack2入栈时如果stack1不为空,则把stack2的元素pop()到stack1;stack2为空就直接push进去。
2. pop(),stack2出栈时如果stack1不为空,则把stack1的元素先pop()到stack2,这样stack2再push()的话元素就是先进先出;stack2为空就直接pop出去。
总之就是stack2用来抛元素,stack1用来倒序。
import java.util.*;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//1,2,3,4
public void push(int node) {
//向stack2 push时,先判断Stack2是否为空,
//如果不为空则将stack2的元素出栈,放进stack1中
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
//stack2为空,则直接放入元素
stack2.push(node);
}
public int pop() {
//栈2元素出栈时先判断栈1是否为空
//如果不为空则将stack1的元素出栈,放进stack2中
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
//栈1为空,此时栈2直接出栈
return stack2.pop();
}
}