废话还是不啰嗦了,直接上代码了
实现方式一:比较傻傻的方法,直接用第一个栈stack1实现压栈,弹栈的话稍微麻烦点了,先把第一个栈的数据压到第二个栈,然后再把第二个栈数据压入第一个栈
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(stack1.isEmpty()){
return 0;
}
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int result=stack2.pop();//需要返回的结果
while (!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return result;
}
}
实现方式二:更好,只用一个循环,参考别人的,思想是当第二个栈没有数据才去第一个栈取,当有数据的时候直接弹栈,就是stack1按顺序入栈的顺序
这是左程云的《程序员代码面试指南》的答案:
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(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}