#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Stackmax 100
#define Stackincrement 10
#define TRUE 1
#define FALSE 0
typedef struct node
{
char *base;
char *top;
int stacksize;
} sqstack;
void initstack(sqstack *s)
{
s->base=s->top=(char *)malloc(sizeof(char)*Stackmax);
if(!s->base) exit(-1);
s->stacksize=Stackmax;
}
void push(sqstack *s,char e)
{
/*if(s->top-s->base>=s->stacksize)//栈溢出
{
s->base=(char *)realloc(s->base,sizeof(char)*(s->stacksize+Stackincrement));
if(!s->base) exit(-1);
s->top=s->base+s->stacksize;
s->stacksize+=Stackincrement;
}
*/
*(s->top)=e;
s->top++;
}
char getpop(sqstack *s)//获取栈顶值
{
char x;
if(s->top!=s->base) x=*(s->top-1);
return x;
}
void pop(sqstack *s)
{
if(s->top!=s->base)
s->top--;
}
int isempty(sqstack *s)
{
if(s->top==s->base)
return TRUE;//true 字体变蓝,是因为本来就有其的存在???
else return FALSE;
}
int main()
{
sqstack s;
char a[101];
int i;
int f;
int len;
while(gets(a))
{
len=strlen(a);
f=1;
initstack(&s);//忘记了!!!
for(i=0; i<=len-1; i++)
{
if(a[i]=='('||a[i]=='{'||a[i]=='[')//右括号入栈
push(&s,a[i]);
else if(a[i]==')')//()
{
if(isempty(&s))//表示右括号多余 空
{
f=0;
break;
}
else
{
if(getpop(&s)!='(')//
{
f=0;
break;
}
else pop(&s);
}
}
else if(a[i]=='}')//{}
{
if(isempty(&s))// 空 左括号多余
{
f=0;
break;
}
else
{
if(getpop(&s)!='{')//
{
f=0;
break;
}
else pop(&s);
}
}
else if(a[i]==']')//[]
{
if(isempty(&s))
{
f=0;
break;
}
else
{
if(getpop(&s)!='[')
{
f=0;
break;
}
else pop(&s);
}
}
}
if(f==1&&isempty(&s))//都匹配成功,即最后栈为空的
printf("yes\n");
else printf("no\n");
}
return 0;
}
数据结构实验之栈与队列四:括号匹配
最新推荐文章于 2020-10-11 15:35:50 发布