数据结构-----栈

来源:互联网 发布:淘宝店铺怎么铺货 编辑:程序博客网 时间:2024/05/16 14:00
栈的定义
     栈(Stack)是限制仅在表的一端进行插入和删除运算的线性表,比数组更抽象的数据结构

  (1)  通常称插入、删除的这一端为栈顶(Top),另一端称为栈底(Bottom)。
  (2)  当表中没有元素时称为空栈。
  (3)  栈为后进先出(Last In First Out)的线性表,简称为LIFO表。
       (4)  栈的基本操作有创建栈,判断栈是否为空,入栈,出栈和取栈顶元素等,其中
              不支持除了栈顶元素对指定位置的插入和删除等操作

             

                                   


import java.util.Stack;/** * Title: 判断表达式中括号是否匹配 * Description: () 匹配  )(不匹配 利用压栈和出栈 * @author Mr Lv * @date 2011-11-26 */public class lzwCode {public static void main(String[] args) {String expstrA = "((1+3)/(7-9))(";System.out.println(expstrA + "===>" + isValid(expstrA));String expstrB = "((1+3)/(7-9))())";System.out.println(expstrB + "===>" + isValid(expstrB));String expstrC = "((1+3)/(7-9))-(0-9)";System.out.println(expstrC + "===>" + isValid(expstrC));}    //判断表达式中括号是否匹配public static String isValid(String expstr) {Stack<String> stack = new Stack<String>();   //现在很少这样用了for (int i = 0; i < expstr.length(); i++) {char ch = expstr.charAt(i);switch (ch) {case '(':stack.push(ch + ""); //左括号入栈break;case ')'://遇到右括号时,左括号出栈,判断出栈字符是否为左括号if (stack.isEmpty() || !stack.pop().equals("(")) { return "缺少左括号(";}}}return (stack.isEmpty()) ? "括号匹配" : "缺少右括号)"; //返回最终信息情况}}


控制台信息: