Fork me on GitHub

括号匹配问题(顺序栈实现)

本周老师作业留了两个。先上传一个吧。那个有时间我再传上来~

本周的要求:

1.给出顺序栈的存储结构定义。
2.完成顺序栈的基本操作函数。
1)      初始化顺序栈
2)      实现入栈和出栈操作
3)      实现取栈顶元素和判空操作
括号匹配问题
3.编写主函数实现基本操作函数功能,并设置测试数据,测试合法和非法数据的输出结果。
4.程序调试运行并保存输出结果。
5.整理并提交实验作业。
#include <cstdio>
#include <cstring>
#define Stack_Size 50
 
typedef struct 
{
    char a[Stack_Size];
    int top;
}SeqStack;

int IsEmpty(SeqStack *S)//栈判空
{
    return S->top == -1;
}
int Match(char ch1,char ch2)//字符串匹配
{
    switch(ch2){
    case ')':
        if(ch1=='(')
            return 1;
        break;
    case '}':
        if(ch1=='{')
            return 1;
        break;
    case ']':
        if(ch1=='[')
            return 1;
        break;
    }
    return 0;
} 
void InitStack(SeqStack * S)//初始化顺序栈
{
    S->top = -1;
} 
void Push(SeqStack * S,char x)//进栈
{
    S->top++;
    S->a[S->top]=x;
} 
void Pop(SeqStack * S,char *x)//出栈
{
    *x=S->a[S->top];
    S->top--;
}

void GetTop(SeqStack * S,char *x)
{
    *x=S->a[S->top]; 
}
 
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右括号多余!\n");
                return ;
            }
            else{
                GetTop(&S,&ch);
                if(Match(ch,str[i]))
                    Pop(&S,&ch);
                else{
                    printf("\n 对应的左右括号不同类!\n");
                    return ;
                }
            }

        }
    }
    if(IsEmpty(&S))
        printf("\n括号匹配!\n");
    else
        printf("\n左括号多余!\n");
}


int main()
{
    char strr[50];
    printf("请输入各种括号\n");
    gets(strr);
    BracketMatch(strr);

    return 0;
}

  

posted @ 2016-10-14 22:18  Jinkelababy  阅读(5144)  评论(2编辑  收藏  举报