数据结构 - 栈

栈是一种后进先出的数据结构,想象成一个 杯子,后面放进去的东西在上面,会被先取出来

以下是用java 数组实现的简单的栈

public class Stack {

    private int top;
    private int maxSize;
    private char[] elements;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        elements = new char[maxSize];
        this.top = -1;
    }

    public void push(char i) {
        if (top == maxSize - 1) {
            throw new RuntimeException("stack is full");
        }
        elements[++top] = i;
    }

    public char pop() {
        if (top == -1) {
            throw new RuntimeException("stack is empty");
        }
        return elements[top--];
    }

    public char peek() {
        return elements[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public static void main(String[] args) {
        Stack stack=new Stack(10);
        stack.push('a');
        stack.push('b');
        stack.push('c');
        System.out.println(stack.isEmpty());
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        //System.out.println(stack.pop()); throw   Exception
    }
}

上面使用栈的数据结果  放入 abc,  打印出来的是 cba,所以,此处使用栈 实现 字符串反转


下面使用 栈 实现简单的  括号匹配 的校验,匹配 {} [] ()

定义一个括号校验器

class BracketCheck{

    private String content;
    public BracketCheck(String content){
        this.content=content;
    }

    public void check(){
        Stack stack=new Stack(content.length());
        for(int i=0;i<content.length();i++){
            char ch=content.charAt(i);
            switch(ch){
                case '{':;
                case '[':;
                case '(':
                    stack.push(ch);
                    break;

                case '}':;
                case ']':;
                case ')':
                    if(!stack.isEmpty()){
                        if( (ch=='}' && stack.pop()!='{') ||
                            (ch==']' && stack.pop()!='[') ||
                            (ch==')' && stack.pop()!='(')   ){
                            throw new RuntimeException("check error");
                        }
                        break;
                    }
                    throw new RuntimeException("check error");
                default:
                    break;
            }

        }
        if(!stack.isEmpty()){
            throw new RuntimeException("check error");
        }
    }
}

以下代码会验证成功

BracketCheck bc=new BracketCheck("{hello world[ni hao a](你呢)}");
bc.check();
System.out.println("check success");

如果去掉最右边的大括号,会抛出异常


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值