c语言实现括号匹配

Modified on: Tue, 30 Jul 2019 10:39:00 +0800 热度: 874 度
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
typedef struct stack{
    char *base;
    int top;
    int max;
}stack;

void InitStack(stack *s,int size)
{
    s->base=(char *)malloc(sizeof(char)*size);
    s->max=size;
    s->top=-1;
}

void pop(stack *s,char elem)
{
    if(s->top>=s->max) return;
    memcpy(&s->base[++(s->top)],&elem,sizeof(char));
}
void push(stack *s,char *elem)
{
    if(s->top<=-1) return;
    memcpy(&*elem,&s->base[(s->top)--],sizeof(char));
}

int main(int argc, char *argv[]) {
    stack sign;
    int len=strlen(argv[1]);
    InitStack(&sign,len);
    int i;
    char temp;
    int flag=1;
    for(i=0;flag&&i<len;i++)
    {
        switch(argv[1][i])
        {
            case '(':
            case '[':
            case '<':
            case '{':
                pop(&sign,argv[1][i]);                
                break;
            case ')':
                
                if(sign.top>=0&&sign.base[sign.top]=='(')
                    push(&sign,&temp);
                else
                {
                    flag=0;
                }
                break;
            case ']':
                if(sign.top>=0&&sign.base[sign.top]=='[')
                    push(&sign,&temp);
                else
                {
                    flag=0;
                }                
                break;
            case '>':
                if(sign.top>=0&&sign.base[sign.top]=='<')
                    push(&sign,&temp);
                else
                {
                    flag=0;
                }
                break;
            case '}':
                 if(sign.top>=0&&sign.base[sign.top]=='{')
                    push(&sign,&temp);
                else
                {
                    flag=0;
                }
        }
    }
    if(flag && sign.top==-1)
        putchar('1');
    else
        putchar('0');
    return 0;
}

添加新评论