来源:互联网 发布:淘宝店铺怎么设置客服 编辑:程序博客网 时间:2024/06/04 19:26
public class StackX {    /*        栈遵后进先出的原则,top索引记录栈顶位置,入栈push,弹出栈pop        是否满ifFull,是否为空ifEmpty,查看栈顶对象peek。     */    private Object[] obj;    private int top;    private int maxSize;    public StackX() {}    public StackX(int maxSize) {        this.maxSize = maxSize;        top = -1;        obj = new Object[maxSize];    }    public void push(Object value) {        obj[++top] = value;    }    public Object pop() {        return obj[top--];    }    public Object peek() {        return obj[top];    }    public boolean isEmpty() {        return top == -1;    }    public boolean isFull() {        return top == (maxSize - 1);    }    //栈应用1:到此逆序,输出"abc",输出"cba"    public String wordReverse(String word) {        String str = "";        StackX stackX = new StackX(word.length());        for (int i = 0; i < word.length(); i++) {            stackX.push(word.charAt(i));        }        while (!stackX.isEmpty()) {            char pop = (char)stackX.pop();            str += pop;        }        return str;    }    //栈应用2:符号匹配,主要进行{}[]()这几种符号的匹配,可以用来检测表达式是否缺少括号。    public void check(String expr) {        StackX stackX = new StackX(expr.length());        for (int i = 0; i < expr.length(); i++) {            char c = expr.charAt(i);            switch (c) {                case '[':                case '{':                case '(':                    stackX.push(c);                    break;                case ']':                case '}':                case ')':                    if(!stackX.isEmpty()) {                        char c1 = (char)stackX.pop();                        if(c == '}' && c1 != '{' || c == ']' && c1 != '[' || c == ']' && c1 != '[') {                            System.out.println("error:" + c + "\tindex at\t" + i);                        }                    } else {                        System.out.println("error:" + c + "\tindex at\t" + i);                    }                    break;                default:                    break;            }        }        if(!stackX.isEmpty())            System.out.println("error:missing delimiter");    }    public static void main(String[] args) {        StackX stackX = new StackX();        String s = stackX.wordReverse("abc");        System.out.println(s);              //cba        stackX.check("a{b[csd(af]}");         /*            error:]index at10            error:}index at11            error:missing delimiter         */    }} 


原创粉丝点击