数据结构实验之栈四:括号匹配
Time Limit: 1000MS Memory limit: 65536K
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10)
{[}]
示例输出
yes
no
Time Limit: 1000MS Memory limit: 65536K
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10)
{[}]
示例输出
yes
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define STACK_INIT_SIZE 100
# define STACKINCREMENT 10
typedef char SelemType;
typedef struct{
SelemType *base;
SelemType *top;
int stacksize;
} SqStack;
void InitStack(SqStack&S);
void Push(SqStack&S,SelemType e);
void Pop(SqStack&S,SelemType&e);
/*栈空返回ture*/
bool StackEmpty(SqStack&S);
void GetTop(SqStack&S,SelemType&e);
int main()
{
//初始化循环变量!!!!!
int i=0;
char str[100];
char etop,epop;
bool match;
SqStack S;
InitStack(S);
while(gets(str))
{
//初始化循环变量!!!!!
int i=0;
//清空上次数据
S.top = S.base;
//设置匹配标志,默认匹配成功
match = true;
while(str[i]!='\0')
{
if(str[i] == '(' || str[i] == '[' || str[i] == '{')
{
Push(S,str[i]);
}
else
{
if(str[i] == ')')
{
if(!StackEmpty(S))
{
GetTop(S,etop);
//栈不空,栈顶为'(',匹配弹出
if(etop == '(')
Pop(S,epop);
//栈不空,栈顶不为'(',失配,如果字符串还有已无再比的需要.
else
{
match = false;
break;
}
}
//如果栈空,出现了‘)'一定不匹配
else
{
match = false;
break;
}
}
if(str[i] == ']' )
{
if(!StackEmpty(S))
{
GetTop(S,etop);
if(etop == '[')
Pop(S,epop);
else
{
match = false;
break;
}
}
else
{
match = false;
break;
}
}
if(str[i] == '}' )
{
if(!StackEmpty(S))
{
GetTop(S,etop);
if(etop == '{')
Pop(S,epop);
else
{
match = false;
break;
}
}
else
{
match = false;
break;
}
}
}
i++;
}
if(StackEmpty(S) && match)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
void InitStack(SqStack&S)
{
S.base = (SelemType*)malloc(STACK_INIT_SIZE*sizeof(SelemType));
if(!S.base)
{
exit(0);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack&S,SelemType e)
{
/*判断栈是否已满*/
if(S.top - S.base >= S.stacksize)
{
/*增大栈的规模*/
S.base = (SelemType*)realloc(S.base,(STACK_INIT_SIZE + STACKINCREMENT) * sizeof(SelemType));
if(!S.base)
{
exit(0);
}
/*重置S.top和S.stacksize*/
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
/*放入添加的元素*/
*S.top = e;
/*栈顶S.top上移*/
S.top++;
//*S.top++ = e;
}
void Pop(SqStack&S,SelemType&e)
{
/*判断栈是否为空,若为空直接返回*/
if(S.top == S.base)
return;
else
{
//e = *--S.top;
/*栈顶下移找到要Pop的元素*/
S.top--;
/*获取要出栈的元素*/
e = *S.top;
}
}
bool StackEmpty(SqStack&S)
{
if(S.top == S.base)
return true;
else
return false;
}
void GetTop(SqStack&S,SelemType&e)
{
if(S.top == S.base)
return;
else
e = *(S.top-1);
}
no