#include <stdio.h>
#include <string.h>
#define M 50
typedef struct node{
char data[M];
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 e){ //入栈
if(S.top==M-1){ //栈满报错
return false;
}
S.data[++S.top]=e;
return true;
}
bool Pop(SqStack &S,char &x){ //出栈
if(S.top==-1){ //栈空报错
return false;
}
x=S.data[S.top--];
return true;
}
bool GetTop(SqStack &S,char &x){ //取栈顶
if(S.top==-1){ //栈空报错
return false;
}
x=S.data[S.top]; //与出栈区别
}
void Init(){
}
bool bracketCheck(char str[],int length){
// Init();
SqStack S;
InitStack(S);
for(int i=0;i<length-1;i++){
if(str[i]=='{' || str[i]=='[' || str[i]=='('){
Push(S,str[i]);
}
else{
if(StackEmpty(S)){
return false;
}
char top;
Pop(S,top);
if(str[i]=='(' && top!=')'){
return false;
}
if(str[i]=='[' && top!=']'){
return false;
}
if(str[i]=='{' && top!='}'){
return false;
}
}
}
return StackEmpty(S); //这里需要判断如果右括号全都匹配了,但是栈中还有左括号残留的情况
//即 如这种情况 {{}
}
int main() {
char s[8]="{{{{}}}"; //char类型数组最后一个是字符'/0'表示结束,所以最多只能初始化7个字符
printf("%d",bracketCheck(s,8));
return 0;
}
栈在括号匹配中的应用
最新推荐文章于 2024-02-27 20:21:47 发布
800

被折叠的 条评论
为什么被折叠?



