栈的应用(括号匹配)
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MAXSIZE 20
typedef struct linkNode
{
char data;
struct linkNode *next;
}Listack;
int InitStack(Listack *&s)
{
s=(Listack *)malloc(sizeof(Listack));
s->next=NULL;
return 0;
}
int push(Listack *&s,char e)
{
Listack *p=(Listack *)malloc(sizeof(Listack));
p->data=e;
p->next=s->next;
s->next=p;
return 0;
}
bool pop(Listack *&s,char &e)
{
Listack *p;
if(s->nextNULL)
return false;
p=s->next;
e=p->data;
s->next=p->next;
return true;
}
int StackEmpty(Listack *s)
{
if(s->nextNULL)
return true;
else
return false;
}
int correct(char *exp,int max)
{
int i,flag=1;
char e,x;
Listack *s;
InitStack(s);
for(i=0;i<max;i++)
{
x=exp[i];
if(x==’(’||x==’{’||x==’[’)
{
push(s,x);
}
if(x==’)’||x==’}’||x==’]’)
{
if(pop(s,e)false)
flag=0; //0表示右括号太多
else if((x’)’&&e!=’(’)||(x==’]’&&e!=’[’)||(x==’}’&&e!=’{’))
flag=-1; //-1表示括号不匹配
}
}
if(StackEmpty(s)==false)
flag=-2; //-2表示左括号太多
return flag;
}
void main()
{
char exp[MAXSIZE];
int j;
while(1)
{
printf("请输入表达式,输入0退出:");
gets(exp);
if(strcmp(exp,"0")==0)
break;
j=correct(exp,strlen(exp));
if(j==0)
printf("内容表达式内容为:\n%s\n表达式右括号多了\n",exp);
else if(j==-1)
printf("内容表达式内容为:\n%s\n表达式的括号不匹配\n",exp);
else if(j==-2)
printf("内容表达式内容为:\n%s\n表达式左括号多了\n",exp);
else
printf("表达式括号匹配\n");
}
}