2015-10-12 【项目3 - 括号的匹配】

来源:互联网 发布:网络作家真实收入 编辑:程序博客网 时间:2024/05/20 09:20

2015-10-12 数据结构实践——括号的匹配(栈)

1.问题及代码

假设表达式中允许三种括号:圆括号、方括号和大括号。编写一个算法,判断表达式中的各种左括号是否与右括号匹配。
例如,输入2+(3+4)*[2+{[3]}-8,输出匹配正确;输入2+(3+4*[2)+{[3]}-8,输出匹配错误。

提示:
(1)遇到左括号入栈,遇到右括号后,出栈一个符号,看是否配对。若配对,继续,直到读完所有的符号,栈也正好为空。若在中间出现一个不配对的,或者____,则可以得出不配对的结论。
(2)也可以设计一个返回值为布尔型的函数,参数为要配对的表达式,为一个字符串。

解法1:

#include <stdio.h>#include "sqstack.h"int main(){    char c;    char st[50];    int d=1, i;    SqStack *s;    InitStack(s);    printf("请输入表达式:");    scanf("%s", st);    for(i=0; st[i]!='\0'&&d; i++)    {        switch(st[i])        {        case'(':        case'[':        case'{':            Push(s, st[i]);            break;        case')':            Pop(s, c);            if(c!='(') d=0;            break;        case']':            Pop(s, c);            if(c!='[') d=0;            break;        case'}':            Pop(s,c);            if(c!='{') d=0;            break;        }    }    if(StackEmpty(s)&&d==1)        printf("配对正确!!\n");    else        printf("配对错误!!\n");    return 0;}


 

解法2:

写成专门的函数

#include <stdio.h>#include "sqstack.h"bool isMatch(char *st){    int d=1, i;    char c;    SqStack *s;    InitStack(s);    for(i=0; st[i]!='\0'&&d; i++)    {        switch(st[i])        {        case'(':        case'[':        case'{':            Push(s, st[i]);            break;        case')':            Pop(s, c);            if(c!='(') d=0;            break;        case']':            Pop(s, c);            if(c!='[') d=0;            break;        case'}':            Pop(s,c);            if(c!='{') d=0;            break;        }    }    if(StackEmpty(s)&&d==1)        return true;    else        return false;}int main(){    char st[50];    printf("请输入表达式:");    scanf("%s", st);    if(isMatch(st))        printf("配对正确!!\n");    else        printf("配对错误!!\n");    return 0;}


 

 

2.运行结果

  出错,原因未知

3.学习心得

 

4.知识总结

0 0