栈在括号匹配中的应用

#define MaxSize 10
bool bracketCheck(char str[], int length) {
	char data[MaxSize];
	int top = -1;
	for(int i = 0; i < length; i++) {
		if(str[i] == '(' || str[i] == '{' || str[i] == '{'){
			if(top == MaxSize - 1)
				return false;
			data[++top] = str[i];
		}
		else{
			if(top == -1)
				return false;
			char topElem = data[top--];
			if(str[i] == ')' && topElem != '(')
				return false;
			if(str[i] == ']' && topElem != '[')
				return false;
			if(str[i] == '}' && topElem != '{')
				return false;
		}
	}
	
	return top == -1;	
}

封装成栈

#define MaxSize 10
typedef strcut {
	char data[MaxSize];
	int top;
} SqStack;

void InitStack(SqStack &S)//初始化栈
void StackEmpty(SqStack S)//判断栈是否为空
bool Push(SqStack &S, char x)//入栈
bool Pop(SqStack &S, char x)//出栈

bool bracketCheck(char str[], int length) {
	SqStack S;
	InitStack(S);
	for(int i = 0; i < length; i++) {
		if(str[i] == '(' || str[i] == '{' || str[i] == '{')
			Push(S, str[i]);
		else{
			if(StackEmpty(S))
				return false;
			char topElem;
			Pop(S, topElem);
			if(str[i] == ')' && topElem != '(')
				return false;
			if(str[i] == ']' && topElem != '[')
				return false;
			if(str[i] == '}' && topElem != '{')
				return false;
		}
	}
	
	return StackEmpty(S);	
}

你可能感兴趣的:(数据结构,数据结构)