目录
栈:先进先出(idea中按住ctrl点进stack能查看方法)
System.out.println(stack.pop()); //弹出栈顶元素,并且删除
System.out.println(stack.peek()); //获取栈顶元素,但是不删除
1.根据逆波兰表达式(也就是后缀表达式),求最大值:
import java.util.Stack;
public class textdemo2 {
public static void main(String[] args) {
Solution ret=new Solution();
int key= ret.evalRPN(new String[]{"2","1","+","3","*"});
System.out.println(key);
}
}
class Solution{
public int evalRPN(String[] tokens){
Stack<Integer> stack =new Stack<>();
for (int i=0;i<tokens.length;i++){
String val=tokens[i];
if(isOperation(val)==false){//不是运算符,是数字,压入栈中
stack.push(Integer.parseInt(val));//stack中传入的必须是字符串,将字符串转换为数字
}else {
int num2=stack.pop();
int num1=stack.pop();
switch (val){
case "+":
stack.push(num1+num2);
break;
case "-":
stack.push(num1-num2);
break;
case "*":
stack.push(num1*num2);
break;
case "/":
stack.push(num1/num2);
break;
}
}
}
return stack.pop();
}
public boolean isOperation(String x){
if(x.equals("+")||x.equals("-")||x.equals("*")||x.equals("/")){
return true;
}
return false;
}
}
2.栈的压入,弹出序列:
import java.util.Stack;
public class textdemo2 {
public static void main(String[] args) {
Solution ret=new Solution();
int[] a={1,2,3};
int[] b ={3,2,1};
boolean key= ret.IsPopOrder(a,b);
System.out.println(key);
}
}
class Solution{
public boolean IsPopOrder(int [] pushA,int[] popA){
Stack<Integer> stack=new Stack<>();
int j=0;
for (int i=0;i<pushA.length;i++){
stack.push(pushA[i]);//把第一个序列的数字挨个输入栈中
}
while (j<popA.length&&!stack.empty()&&stack.peek()==popA[j]){
stack.pop();//当数字相等时,弹出
j++;
}
return stack.empty();
}
}
链表实现栈:①先进后出;②入栈和出栈时间复杂度是o(1) —用双链表
3.字符串匹配:
括号必须以正确的顺序闭合;左括号用相同的类型和右括号匹配