顺序栈(括号匹配的检验)

#pragma warning(disable:4996)
#include
#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
//顺序栈
typedef struct {
	char *base;
	char *top;
	int stacksize;
}SqStack;

int InitStack(SqStack &S) {
	//构造一个空栈S
	S.base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
	if (!S.base) exit(OVERFLOW);
	S.top = S.base;
	S.stacksize = STACK_INIT_SIZE;
	return 1;
}
int GetTop(SqStack S, char &e) {
	//若栈不空,则用e返回栈顶元素,并返回ok(1),否则返回error(0)
	if (S.top == S.base)return 0;
	e = *(S.top - 1);
	return 1;
}
int Push(SqStack &S, char e) {
	//插入元素e为新的栈顶元素
	if (S.top - S.base >= S.stacksize) {//栈满,追加存储空间
		S.base = (char*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(char));
		if (!S.base)exit(OVERFLOW);//存储分配失败
		S.top = S.base + S.stacksize;
		S.stacksize += STACKINCREMENT;
	}
	*(S.top++) = e;
	return 1;
}
int Pop(SqStack &S, char &e) {
	//若栈不为空,则删除S的栈顶元素,用e返回其值,并返回ok,否则返回error
	if (S.top == S.base)return 0;
	e = *(--S.top);
	return 1;
}
char s[1000];
bool isEmpty(SqStack sta) {
	//判断栈是否为空
	if (sta.top == sta.base)return 1;
	return 0;
}
void PrintStack(SqStack s) {
	if (isEmpty(s))return;
	printf("Stack:");
	while (!isEmpty(s))
	{
		printf("%c ", *(s.top - 1));
		char e;
		Pop(s, e);
	}
	printf("\n");
}
bool isMatch(char *s) {
	SqStack sta;
	InitStack(sta);
	bool flag = 1;
	char t;
	int cnt = 0,sum=0;
	for (int i = 0; i < strlen(s)&&flag; i++) {
		if (s[i] == '(' || s[i] == ')') {//只判断串中圆括号是否匹配
			if (s[i] == '(')//如果是左括号,入栈
				Push(sta, s[i]);
			else if ((s[i] == ')') && (!isEmpty(sta)))
			{//如果是右括号并且栈非空
				Pop(sta, t);
				//printf("%c\n", t);
			}
			else {//右括号且栈空
				flag = 0;
			}
		}
	}
	PrintStack(sta);
	if (isEmpty(sta)&&flag) {
		return 1;
	}
	return 0;
}
int main() {
	strcpy(s, "[{[()()()()}]]{");
	if (isMatch(s))
		printf("%s is Match\n",s);
	else
		printf("%s is Not Match\n",s);
	system("pause");
	return 0;
}

 

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