import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
stack1.push(node);
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
public int pop() {
return stack1.pop();
}
}
另一种思路:
链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?answerType=1&f=discussion
来源:牛客网
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.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
剑指offer 两个栈实现队列
最新推荐文章于 2022-11-29 20:52:14 发布