
#include"stdio.h"
#include"string.h"
#define MAXSIZE 100
typedef struct Stack{
char a[MAXSIZE];
int top;
}SqlStack;
void initStack(SqlStack &s) {
s.top = -1;
}
void push(SqlStack &s, char e) {
s.a[++s.top] = e;
}
char pop(SqlStack &s) {
char popE = s.a[s.top--];
return popE;
}
char peek(SqlStack &s) {
return s.a[s.top];
}
int main()
{
SqlStack s;
initStack(s);
int matchSuccess = 1;
char expression[] = "[ ( 10 + 2 ) * 3 - [ 5 / ( 1 + 1 ) ] ]";
int len = strlen(expression);
for (int i = 0; i < len && matchSuccess; i++) {
if (expression[i] == '[' || expression[i] == '(') {
push(s, expression[i]); // 左括号入栈
}
else if (expression[i] == ']' || expression[i] == ')') {
if (s.top == -1) { // 栈空,右括号多于左括号
matchSuccess = 0;
break;
}
char topChar = pop(s);
// 检查括号是否匹配
if ((expression[i] == ']' && topChar != '[') ||
(expression[i] == ')' && topChar != '(')) {
matchSuccess = 0;
break;
}
}
}
if (matchSuccess && s.top == -1) {
printf("success: 括号匹配正确\n");
} else {
printf("wrong: 括号不匹配\n");
}
return 0;
}