栈应用--括号匹配检测

//---------------------------kuohao.c------------------------------
/*
    使用方法 
    gcc kuohao.c -o kuohao
    ./kuohao name    name待检测的文件
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef char Elemtype;
#define  StackMaxSize  100
struct Stack
{
    Elemtype stack[StackMaxSize];
    int top;
};

static void init_stack(struct Stack * H)
{
    H=(struct Stack *) malloc (sizeof(struct Stack));
    if(H==NULL)
    {
        printf("malloc error/n");
        exit(-1);
    }
}

static void  push_stack(struct Stack *H, Elemtype item)
{
    if(H->top==StackMaxSize-1)
    {
        printf("Stack fully/n");
        exit(-1);
    }
    H->top++;
    H->stack[H->top]=item;
}

static Elemtype pop_stack(struct Stack *H)
{
    Elemtype e;
    if((H->top)<0)
    {
        printf("又括号太多/n");
        return -1;
    }
    e=H->stack[H->top];
    H->top--;
    return e;
}

//上面代码是用于实现栈的代码

int main(int argc, char *argv[])
{
    if(argc!=2)
    {
        printf("请输入命令名和文件明/n");
        exit(-1);
    }

    FILE *fp;
    char ch;

    struct Stack *S;
    init_stack(S);
    S->top=-1;

    fp=fopen(argv[1],"r");
   
    while((ch=getc(fp))!=EOF)
    {
        if(ch=='(' | ch=='{' | ch=='[' | ch=='<')
        {
            push_stack(S,ch);
        }
        else if(ch==')' | ch=='}' | ch==']' | ch=='>')
        {//如果是右括号,那就出栈比较吧
            switch(ch)
            {
                case ')':
                    if(pop_stack(S)!='(')
                    {
                        printf("匹配错误/n");
                        exit(-1);
                    }
                    break;
                case '}':
                    if(pop_stack(S)!='{')
                    {
                        printf("匹配错误/n");
                        exit(-1);
                    }
                    break;
                case ']':
                    if(pop_stack(S)!='[')
                    {
                        printf("匹配错误/n");
                        exit(-1);
                    }
                    break;
                case '>':
                    if(pop_stack(S)!='<')
                    {
                        printf("匹配错误/n");
                        exit(-1);
                    }
                    break;
            }
        }
        else//如果是空格,字符之类,则什么也不做
        {
        }
    }
    if(S->top!=-1)
    {
        printf("左括号太多/n");
        exit(-1);
    }
    printf("完全匹配^_^/n");
    exit(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值