#include <stdio.h>
#include <stdlib.h>
#define MaxSize 30 //定义栈中最大元素
typedef struct{
char data[MaxSize]; //静态数组中存放最大元素
int top; //栈顶指针(下标)
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top = -1;
}
//判断栈空
bool StackEmpty(SqStack S){
if(S.top == -1)
return true; //空
else
return false; //不空
}
//入栈操作
bool Push(SqStack &S, char x){
if(S.top == MaxSize-1){
return false; //栈满
}
else{
S.top += 1;
S.data[S.top] = x;
return true;
}
}
//出栈
char Pop(SqStack &S, char &x){
if(S.top == -1){
return false;
}
else{
x = S.data[S.top];
S.top--;
return x;
}
}
//括号匹配
bool bracketCheck(SqStack S, char str[], int length){
for(int i = 0; i < length ; i++){
if(str[i] == '(' || str[i] == '[' || str[i] == '{'){ //扫描左括号入栈
Push(S, str[i]);
}
else if(StackEmpty(S)){ //扫到右括号或者空栈
return false; //匹配失败
}else{
char topElem;
topElem = Pop(S, topElem); //栈顶元素出栈
/* printf("%c",topElem); */
if (str[i] == ')' && topElem != '('){
return false;
}
if (str[i] == ']' && topElem != '['){
return false;
}
if (str[i] == '}' && topElem != '{'){
return false;
}
}
}
}
int main(){
SqStack S;
InitStack(S);
char str[30];
int h;
printf("输入要检查的括号数量:");
scanf("%d", &h);
fflush (stdin);
printf("请输入括号:");
for (int i = 0; i < h; i++)
{
scanf("%c", &str[i]);
}
if (bracketCheck(S, str, h)){
printf("匹配成功\n");
}
else
printf("匹配失败\n");
system("pause");
}
运行示例
如有错误请指正!