Java学习笔记

1.数组不支持范型 可以通过object来替代范型,在把object型转为范型时需要强转 

package com.lzy.stack;
/*
 * 数组不支持范型 可以通过object来替代范型,在把object型转为范型时需要强转
 * 
 */
public class MyArrayStack<T> {
    
    private Object[] items; //数组
    private int count;  //栈中元素个数
    private int n;    //栈容量
    
    //构造函数 初始化
    public MyArrayStack(int n) {
        //this.items = new T[n];    编译不通过
        this.items = new Object[n]; //使用正确
        this.count = 0;    
        this.n = n;
    }
    
    public boolean push(T item) {
        //栈空间已满 返回false
        if(count == n) return false;
        //栈空间未满 在栈顶加入新元素 返回true
        items[count] = item;
        count ++;    //栈顶加1
        return true;
    }
    
    public T pop() {                  
        if(count == 0) return null;
        T temp = (T)items[count - 1];     //需要强装类型 把Object型转为范型
        count --;
        return temp;
    }
    
    public String toString() {
        String temp = "[";
        for(int i = 0; i < count; i++) {
            temp += items[i];
            temp += ",";
        }
        temp = temp.substring(0, temp.length()-1);
        temp += "]";
        return temp;
    }
}
View Code

 

 2.链表实现栈 头插法 链表头天生是栈顶

package com.lzy.stack;

public class Node {
    public Object element;
    public Node next;
    
    public Node(Object element) {
        this(element,null);
    }
    
    public Node(Object element,Node next) {
        this.element = element;
        this.next = next;
    }
    
    public Object getElement() {
        return element;
    }
    
    
    
}




package com.lzy.stack;

public class MyListStack {
    Node header; //栈顶元素 头插法 链表头天生是栈顶 
    int count;  //栈中元素个数
    int size;   //栈容量
    
    //构造函数 初始化栈
    public MyListStack(int size) {
        header = null;
        count = 0;
        this.size = size;
    }
    
    public boolean push(Object value) {
        //栈满
        if(count == size) return false;
        //栈不满
        header = new Node(value,header);
        count ++;
        return true;
        
    }
    
    public Object pop() {
        //栈空
        if(count == 0) return null;
        //栈不空
        Object object = header.element;
        header = header.next;
        count--;
        return object;
    }
    
    public String toString() {
        String temp = "[";
        while(header != null) {
            temp += header.element;
            temp += ",";
            header = header.next;
        }
        temp = temp.substring(0,temp.length() - 1);
        temp += "]";
        return temp;
    }
}
View Code

 

3.栈实现括号匹配算法

https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/

package com.lzy.leetcode;

import java.util.HashMap;
import java.util.Stack;

/*
 * 括号匹配
 */
public class Kuohaopipei {
    // Hash table that takes care of the mappings.
      private HashMap<Character, Character> mappings;

      // Initialize hash map with mappings. This simply makes the code easier to read.
      public Kuohaopipei() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
      }

      public boolean isValid(String s) {

        // Initialize a stack to be used in the algorithm.
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);

          // If the current character is a closing bracket.
          if (this.mappings.containsKey(c)) {       //containsKey方法有这个key就返回true 
                                                      //containsValue方法 有这个value就返回true

            // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
            char topElement = stack.empty() ? '#' : stack.pop();

            // If the mapping for this bracket doesn't match the stack's top element, return false.
            if (topElement != this.mappings.get(c)) {
              return false;
            }
          } else {
            // If it was an opening bracket, push to the stack.
            stack.push(c);
          }
        }

        // If the stack still contains elements, then it is an invalid expression.
        return stack.isEmpty();
      }    
}
View Code

 

4.运行时报错 RuntimeException("自定义的报错信息"),不需要导入包就可以直接使用。

 

5.两个栈实现简单计算器

使用两个栈,一个用来存储操作符(opr),一个用来存储数字(num),在遍历时:

遇到加、减、乘、除、左括号,放进opr里面;
遇到数字,把完整的数字记下来,然后看opr的顶部如果是乘或除的话,就作一次运算,结果还是放进num栈里面;
遇到右括号,因为第二步可以保证乘除已经实现运算完了,所以左右括号区间的opr里面只剩加和减了,把区间内的num按opr是加还是减求和即可,结果依然放进num中;
做完以上遍历后,opr里面应该还会剩一堆加减符号,最后一步还是按类似步骤三的方法求一遍和,就能得到答案了。
有一个小细节,就是可能会遇到开头是“-”的表达式,例如“-1+1”,我们可以事先在num栈里面放一个0以应对这种情况(可以推一下,事先放一个0是不会影响到正常情况的)。

https://leetcode-cn.com/problems/basic-calculator/solution/c-chang-gui-de-liang-ge-zhan-de-jie-fa-by-cyiano/

public class Calculate2{
/*
 * 使用两个栈,一个用来存储操作符(opr),一个用来存储数字(num),在遍历时:

遇到加、减、乘、除、左括号,放进opr里面;
遇到数字,把完整的数字记下来,然后看opr的顶部如果是乘或除的话,就作一次运算,结果还是放进num栈里面;
遇到右括号,因为第二步可以保证乘除已经实现运算完了,所以左右括号区间的opr里面只剩加和减了,把区间内的num按opr是加还是减求和即可,结果依然放进num中;
做完以上遍历后,opr里面应该还会剩一堆加减符号,最后一步还是按类似步骤三的方法求一遍和,就能得到答案了。
有一个小细节,就是可能会遇到开头是“-”的表达式,例如“-1+1”,我们可以事先在num栈里面放一个0以应对这种情况(可以推一下,事先放一个0是不会影响到正常情况的)。

 */
    public int calculate(String s) {
    //两个栈实现简易计算器
        Stack<Character> opr = new Stack<>();
        Stack<Integer> num = new Stack<>();
        num.push(0);
        int index = 0;  //位置索引,逐渐先后,采用编译原理的思路
        while(index < s.length()) {
            if(s.charAt(index) == ' ') { //如果是空格,直接跳过
                index++;
            }else if(s.charAt(index) == '(' || s.charAt(index) == '+' || s.charAt(index) == '-' || s.charAt(index) == '*' || s.charAt(index) == '/') {
                //如果是( + - * / 就入符号栈
                opr.push(s.charAt(index));
                index++;
            }else if (s.charAt(index) == ')' ) { //如果是右括号
                int sum = 0;
                
                while( opr.peek() != '(') {
                      char op = opr.pop();
                     //opr.pop();
                     int n = num.pop();
                    sum += op == '+' ? n : -n; 
                }
                int n = num.pop();
                sum += n;
                opr.pop();
                num.push(sum);
                index++;
            }else { //只剩下数字
                String temp = "";
                while(index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                    temp += s.charAt(index);
                    index++;
                }
                //把数字入栈 
                num.push(Integer.valueOf(temp));
                //数字入栈后,如果符号栈栈顶元素为* / 则进行计算
                
                if(!opr.isEmpty() && ( opr.peek() == '*' || opr.peek() == '/')) {
                    char op = opr.pop();
                    int sum = 0;
                    int second = num.pop();
                    int first = num.pop();
                    sum = op == '*' ? first * second : first / second;
                    num.push(sum);
                }
                
            }
        }
        //最后符号栈只剩下+ - 把所有数据合起来就行
        int sum = 0;
        while(!opr.isEmpty()) {    
            char op = opr.pop();
            int n = num.pop();
            sum += op == '+' ? n : -n;
        }
        
        return sum + num.pop();
        
    }
    
    public static void main(String[] args) {
        Calculate2 c = new Calculate2();
        int n = c.calculate("(1+(4+5+2)-3)+(6+8)");
        System.out.println(n);
    }
}
View Code

 

转载于:https://www.cnblogs.com/jianghuxiao/p/11536922.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值