括号匹配问题
1.实验类别:基础
2.实验目的:
(1)掌握栈定义及实现。
(2)利用栈解决实际问题。
3.实验主要内容:
假设一文本文件中保存有若干行代码,代码中有圆括弧()、方括弧[]和花括弧{}3种类型的括弧。编写程序,实现自动判别表达式中括弧是否正确匹配。
要求:(1)从文件中读入内容。
(2)要求能判断出以下几种情形:括号匹配、首次括号不匹配出现的位置及常见情形(缺少右括号、右括号多余和左右括号不匹配)。
4.实验类型:综合、设计
5.实验要求:必修
# include <stdio.h>
# include <malloc.h>
int col;
int row=0;
int flag=0;//立个flag
//定义数据域类型
typedef struct Data
{
char Node;
int row;
int col;
}datatype;
//定义栈
typedef struct node
{
datatype data;
struct node * next;
}StackNode ,* LinkStack;
//定义初始化函数
//返回值top:栈顶指针
LinkStack Init_LinkStack(void)
{
LinkStack top=(LinkStack)malloc(sizeof(StackNode));
top->next=NULL;
return top;
}
//定义判断空值函数
//返回值1:说明栈为空
//返回值0:说明栈不为空
int Empty_Linkstack(LinkStack top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
//定义入栈函数
//参数top:栈顶指针 参数x:入栈的数据
//返回值top:新的栈顶指针
LinkStack Push_LinkStack (LinkStack top, char x)
{
LinkStack s=(LinkStack)malloc(sizeof(StackNode));
(s->data).Node=x;
s->next=top;
top=s;
return top;
}
//定义出栈函数
//参数top:栈顶指针
//返回值top:新的栈顶指针
LinkStack Pop_LinkStack (LinkStack top)
{
LinkStack p;
p = top;
top = p->next;
free(p);
p=NULL;
return top;
}
//定义取栈顶元素指针
//参数top:栈顶指针 参数x:char类型指针
//返回值0:说明栈空不能取 返回值1:说明取栈顶元素成功
int Top_LinkStack(LinkStack top, char * x)
{
if(Empty_Linkstack(top)==1)
return 0;
else
{
*x=(top->data).Node;
return 1;
}
}
//定义匹配函数
//参数top:栈顶指针 参数str[]:存放每行读取的符号
//返回值:新的栈顶指针
LinkStack Correct(LinkStack top,char str[])
{
int i,j;
char x;
row++;
for(i=0;str[i]!='\0';i++)
{
col=i+1;
if(str[i]=='{'||str[i]=='['||str[i]=='(')
{
top=Push_LinkStack(top,str[i]);
(top->data).col=i+1;
(top->data).row=row;
}
if(str[i]=='}'||str[i]==']'||str[i]==')')
{
Top_LinkStack(top, &x);
if(Empty_Linkstack(top)==0)//栈不为空
{
if((str[i]=='}'&&x=='{')||(x=='('&&str[i]==')')||(x=='['&&str[i]==']'))
{
top=Pop_LinkStack(top);
}
else
{
if(flag==0)
{
printf("错误:第%d行第%d列右边%c没有和左边的%c相匹配\n",row,col,str[i],(top->data).Node);
flag=1;
}
}
}
else
{
if(flag==0)
{
printf("错误:第%d行第%d列的%c多余\n",row,col,str[i]);
flag=1;
}
}
}
}
return top;
}
//定义匹配函数2
//参数top:栈顶指针
//返回值top:栈顶指针
LinkStack Correct_2(LinkStack top)
{
char x,m;
if(flag==0)//以上程序没输出--即没错误
{
if(Empty_Linkstack(top)==0) //栈不为空
{
Top_LinkStack(top, &x);
if(x=='(')
{
m=')';
}
if(x=='[')
{
m=']';
}
if(x=='{')
{
m='}';
}
printf("错误:第%d行第%d列缺失了%c\n",row,col,m);
}
if(Empty_Linkstack(top)==1)//栈为空
{
printf("括号匹配完全正确\n");
}
}
return top;
}
int main()
{
FILE *fp;
LinkStack top=Init_LinkStack();
char str[128];
if((fp=fopen("test.txt","r"))==NULL)
{
printf("cannot open file\n");
return 0;
}
while(!feof(fp))
{
if(fgets(str,128,fp)!=NULL)
top=Correct(top,str);
}
top=Correct_2(top);
free(top);
top=NULL;
fclose(fp);
}