栈 括号匹配

来源:互联网 发布:手机淘宝用户怎么注册 编辑:程序博客网 时间:2024/06/11 09:58
#include <cstdio>
#include <stdlib.h>
#define Stack_size 100
typedef char ElemType;
typedef struct Node
{
    ElemType elem[Stack_size];
    int top;
} Seqstack;
void Initstack (Seqstack *s)
{
    s->top=-1;
}
int Push(Seqstack *s, ElemType x)  //将元素x入栈
{
    if(s->top==Stack_size-1) return false;
    s->top++;
    s->elem[s->top]=x;
    return true;
}

int Pop(Seqstack *s, ElemType *x)   //将栈顶元素出栈 通过x带出
{
    if(s->top==-1) return false;
    else{
        *x=s->elem[s->top];
        s->top--;
        return true;
    }
}

int Gettop(Seqstack *s, ElemType *x) //读出栈顶元素 通过x带出
{
    if(s->top==-1) return false;
    else{
        *x=s->elem[s->top];
        return true;
    }
}

int Isempty(Seqstack *s)  //判断栈是否为空 空的话返回1  非空返回0
{
    if(s->top==-1) return true;
    else return false;
}

int IsFull(Seqstack *s ) //判断栈是否满了 满的话返回1  不满返回0
{
    if(s->top==Stack_size-1) return true;
    else return false;
}

int Match(char a,char b)
{
    if(a=='(' && b==')') return 1;
    if(a=='{' && b=='}') return 1;
    if(a=='[' && b==']') return 1;
    return 0;
}
void BracketMatch(char *str )
{
    Seqstack s;char ch;
    Initstack(&s);
    for(int i=0;str[i]!='\0';i++)
    {
        switch(str[i])
        {
        case '(':
        case '[':
        case '{':
            Push(&s,str[i]);
            break;
        case ')':
        case ']':
        case '}':
            if(Isempty(& s)) {
                    printf("匹配不成功\n");
                    return ;
            }
            else{
                Gettop(&s,&ch);
                if(Match(ch,str[i])) Pop(&s,&ch);
                else {
                        printf("匹配不成功\n");
                        return;
                }
            }
        }
    }
    if(Isempty(&s)) printf("匹配成功\n");
    else printf("左括号多余\n");
}
int main()
{
    char str[20];
    printf("请输入要匹配的括号\n");
    scanf("%s",&str);
    BracketMatch(str);
    return 0;
}
原创粉丝点击