问题及算法:
/*
烟台大学计算机学院
文件名称:main.cpp
作者:王效杰
完成日期:2017年10月12日
问题描述:定义链栈存储结构,实现其基本运算
输入描述:无
输出描述:链栈的操作以及栈的操作后的元素输出,以及出栈的元素输出
*/
#include <stdio.h>
#include "ltsk.h"
int main()
{
char c;//出栈用到
char st[50];
int d=1, i;//d用来记录是否配对
LinkStNode *s;
InitStack(s);
while(1)
{
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;
}
运行结果:
学习心得:
学会了如何判断表达式的括号配对。但是此程序有bug 例如:())));{}}}}};[]]]]。此程序都判断的不正确。
分析程序应该是没判断栈空之后的情形。