|
发表于 2018-6-14 15:27:12
|
显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define BUFFERSIZE 256
int BracketMatch(SqStack *S,const char *string);
int BracketMatch(SqStack *S,const char *string)//括号是否匹配,是则返回TURE,否则返回FALSE
{
const char *p=string;
while(*p!='\0')
{
switch(*p)
{
case '(':
case '[':
case '{':
Push(S,*p);
break;
case ')':
if(GetTop(*S)=='(') Pop(S);
else return FALSE;
break;
case ']':
if(GetTop(*S)=='[') Pop(S);
else return FALSE;
break;
case '}':
if(GetTop(*S)=='{') Pop(S);
else return FALSE;
break;
default:
printf("请勿输入非法字符!");
break;
}
p++;
}
if(!StackEmpty(*S))//字符串遍历完,栈非空,不匹配
return FALSE;
return TRUE;
}
int main()
{
char *string;
SqStack stack;
InitStack(&stack);
string=(char*)malloc(BUFFERSIZE*sizeof(char));
if(!string){
printf("string分配内存失败.\n");
exit(0);
}
printf("请输入一行含括号的表达式(输入\"!\"退出):");
gets(string);
while(1)
{
if(string[0]=='!') break;
if(BracketMatch(&stack,string)) printf("括号匹配\n");
else printf("括号不匹配\n");
printf("请输入一行含括号的表达式(输入\"!\"退出):");
gets(string);
}
return 0;
} |
|