Java 栈

目录

 

1.根据逆波兰表达式(也就是后缀表达式),求最大值:

2.栈的压入,弹出序列:

3.字符串匹配:

栈:先进先出(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.字符串匹配:

括号必须以正确的顺序闭合;左括号用相同的类型和右括号匹配

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值