<div><pre name="code" class="cpp">/*Copyright (c) 2015,烟台大学计算机学院
*All right reserved
*文件名称:sqstack.cpp
*作者:贾召飞
*完成日期:2015年10月13日 17:41
*版本号:v1.0
*
*问题描述:匹配括号
*/
#include <stdio.h>
#include<iostream>
using namespace std;
#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;
}
学习心得:
栈空时执行Pop,会“失败”而返回false。若发生这种情况,实则已经是栈中已无左括号,但串中仍有右括号,属于不匹配。问题就是这样产生的,如何修改,交给读者您自己来吧。