5、用两个栈实现队列
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()){//2空了,1没空
while(!stack1.empty()){
stack2.push(stack1.pop());//1的栈顶出栈,到2的栈底 压栈
}
}
return stack2.pop();//2的栈顶(1的栈底),出栈,等效于先进先出——队列
}
}
20、包含min函数的栈
Java 代码中,由于 Stack 中存储的是 int 的包装类 Integer ,因此需要使用 equals() 代替 == 来比较值是否相等
class MinStack {
Stack<Integer> A, B;
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.add(x);//A入栈
if(B.empty() || B.peek() >= x)
B.add(x);//如果B为空,或B的栈顶>=x,x入栈 —— 保证自上而下 是递增的
}
public void pop() {
if(A.pop().equals(B.peek()))
B.pop();//A出栈的元素=B的栈顶,B出栈
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}
21、栈的压入弹出序列
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 || popA.length == 0)
return false;
Stack<Integer> s = new Stack<Integer>();
//用于标识弹出序列的位置
int popIndex = 0;
for(int i = 0; i< pushA.length;i++){
s.push(pushA[i]);
//如果栈不为空,且栈顶元素等于弹出序列
while(!s.empty() &&s.peek() == popA[popIndex]){
//出栈
s.pop();
//弹出序列向后一位
popIndex++;
}
}
return s.empty();
}
}