import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack2.push(node);
}
public int pop() {
if(stack1.empty()){
while(!stack2.empty()){
stack1.push(stack2.pop());
}
}
return stack1.pop();
}
}我这是把每次读取把1的弹到2 然后取最底部的 然后又把 2 的弹回1 中
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() {
int res = 0;
while(stack1.size() != 1){
int temp = stack1.pop();
stack2.push(temp);
}
res = stack1.pop();
while(stack2.size() != 0){
int temp = stack2.pop();
stack1.push(temp);
}
return res;
}
}其实 不用
只要判断 2 不为空 就可以一直弹2
2空了 再把1中的弹进来就好了
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int ret = stack2.top();
stack2.pop();
return ret;
}
private:
stack<int> stack1;
stack<int> stack2;
};


京公网安备 11010502036488号