/*
*Copyright (c) 2017,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:单链表应用逆置、连接与递增判断
*作 者:高晶
*完成日期:2017年11月07日
*版 本 号:v1.0
* 数据结构实践——括号的匹配(栈)
*/
【项目 - 括号的匹配】
假设表达式中允许三种括号:圆括号、方括号和大括号。编写一个算法,判断表达式中的各种左括号是否与右括号匹配。
例如,输入2+(3+4)*2+{[3]}-8,输出匹配正确;输入2+(3+4*[2)+{[3]}-8,输出匹配错误。
解法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;
}
运行结果: