#include<stdio.h>
#define MAXSIZE 20
typedef struct {
char data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack* S) {
S->top = -1;
/*for (int i = 0; i < MAXSIZE; i++) {
S->data[i] = 0;
}*/
}
int StackEmpty(SqStack S) {
if (S.top == -1) {
return 1;
}
else {
return 0;
}
}
int push(SqStack* S, char x) {
if (S->top + 1 > MAXSIZE) {//s->top=MAXSIZE-1
return 0;
}
S->top += 1;
S->data[S->top] = x;
return 1;
}
int pop(SqStack* S, char *x) {
if (StackEmpty(*S)) {
return 0;
}
*x = S->data[S->top];//这里解引用x
S->top -= 1;
return 1;
}
int bracketCheck(char * str, int length) {
SqStack S;
InitStack(&S);
int i = 0;
for ( i = 0; i < length; i++) {
//printf("%c ", *(str+i));
if (*(str + i) == '(' || *(str + i) == '[' || *(str + i) == '{') {
push(&S, *(str + i));
}
else {
if (StackEmpty(S)) {
return 0;//若匹配的是右括号且栈为空,出错了
}
char topeElem;
pop(&S, &topeElem);
if (* (str + i) == ')' && topeElem != '(') {
return 0;
}
if (*(str + i) == ']' && topeElem != '[') {
return 0;
}
if (*(str + i) == '}' && topeElem != '[') {
return 0;
}
}
}
return StackEmpty(S);//检索完如果栈为空
}
int arr(char str[]) {
for (int i = 0; i < 2; i++) {
printf("%c", str[i]);
}
}
int main() {
char str[] = { '[',']' };
//arr(str);
/*SqStack S;
InitStack(&S);
int r1=push(&S, arr[0]);
printf("%d\n", r1);
char x1=' ';
char x = pop(&S, &x1);
printf("%c", x1);*/ //测试出栈,入栈是否正常
int result=bracketCheck(str, 2);
printf("%d\n", result);
}