#include <cstdio>
#include <iostream>
using namespace std;
#define MAXSIZE 20
typedef struct {
char *base;
char *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S)
{
S.base = (char *)malloc( MAXSIZE * sizeof(char) );
if(S.base == NULL) exit(-2);
S.top = S.base;
S.stacksize = MAXSIZE;
}
void GetTop(SqStack S, char &e)
{
if(S.top == S.base)
return;
e = *(S.top - 1);
}
void Push(SqStack &S, char e) // 不考虑栈满
{
*S.top++ = e;
}
void Pop(SqStack &S, char &e)
{
if(S.top == S.base)
return;
S.top--;
e = *S.top;
}
bool Match(char c, SqStack &my_stack, bool &tag)
{
char e;
Pop(my_stack, e);
if ( c != e ) {
tag = false;
free(my_stack.base);
return false; // match fail
}
return true; // match success
}
void Correct(char *expr, bool &tag)
{
tag = true;
SqStack my_stack;
InitStack (my_stack);
for( int i = 0; expr[i] != '\0'; i++ ) {
char c = expr[i];
switch(c) {
case '{' : case '[' : case '(' :
Push (my_stack, c); break;
case '}' :
if( Match('{', my_stack, tag) == false ) // match fail
return;
break;
case ']' :
if( Match('[', my_stack, tag) == false ) // match fail
return;
break;
case ')' :
if( Match('(', my_stack, tag) == false ) // match fail
return;
break;
default :
break; // 其它字符
}
}
if(my_stack.top != my_stack.base) // e.g.: "[r"
tag = false;
free(my_stack.base);
}
int main(void)
{
// freopen("cin.txt", "r", stdin);
char my_expr[MAXSIZE];
while(cin >> my_expr) {
bool tag = true;
Correct( my_expr, tag);
tag ? printf("匹配成功\n") : printf("匹配失败\n");
}
return 0;
}
括号匹配(栈实现)
最新推荐文章于 2022-11-03 15:07:46 发布