`
bcyy
  • 浏览: 1823482 次
文章分类
社区版块
存档分类
最新评论

括号匹配(栈实现)

 
阅读更多

#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;
}


(另见 http://blog.csdn.net/justme0/article/details/7424798

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics