如题,参考王道论坛
#include<stdio.h>
#define MaxSize 6
typedef struct {
char data[MaxSize];//静态数组存放栈中元素
int top;//栈顶指针
}SqStack;
//初始化栈
void InitStack(SqStack& S) {
S.top = -1;
}
//新元素入栈
bool Push(SqStack& S, char x) {
if (S.top == MaxSize - 1)
return false;
else {
S.top = S.top + 1;
S.data[S.top] = x;
}
return true;
}
//判断栈空
bool StackEmpty(SqStack S) {
if (S.top == -1)
return true;
else
return false;
}
//出栈
bool Pop(SqStack& S, char &x) {
if (S.top == -1)
return false;
x = S.data[S.top];
S.top--;
return true;
}
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);
}
int main() {
char str[] = { '{','[',']'};
if (bracketCheck(str, sizeof(str)))
printf("success");
else
printf("fail");
return 0;
}