第六周 项目3 括号的匹配

来源:互联网 发布:耐克淘宝旗舰店正吗 编辑:程序博客网 时间:2024/04/28 22:39
/* Copyright (c).2014, 烟台大学计算机学院 All rights reserved. 文件名称:test.cpp 作    者:吕云双 完成日期:2015年 10 月 11日 题目要求:(1)遇到左括号入栈,遇到右括号后,出栈一个符号,看是否配对。若配对,继续,直到读完所有的符号,栈也正好为空。若在中间出现一个不配对的,或者____,则可以得出不配对的结论。 (2)也可以设计一个返回值为布尔型的函数,参数为要配对的表达式,为一个字符串。 版 本 号:v1.0 */

#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;}
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">函数和主函数:</span>
#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;}
运行结果:
<img src="http://img.blog.csdn.net/20151012164122043?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
知识点:
<img src="http://img.blog.csdn.net/20151012164301122?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
0 0