王道考研-数据结构中的p27 3.3.1_栈在括号匹配中的应用
3.3.1_栈在括号匹配中的应用_哔哩哔哩_bilibili
视频中写出了各个方法,这里写了个主函数和测试数据
#include<iostream>
using namespace std;
#define MaxSize 10
typedef struct{
char data[MaxSize]; //存储栈中元素
int top; //栈顶指针
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top = -1;
}
//栈判断是否为空
bool StackEmpty(SqStack S){
return S.top == -1;
}
//判断栈是否为满
bool StackFull(SqStack &S){
return S.top == MaxSize - 1;
}
//入栈
bool Push(SqStack &S , char x){
if(StackFull(S)) return false;
S.data[++S.top] = x;
return true;
}
//出栈
bool Pop(SqStack &S , char &x){
if(StackEmpty(S)) return false;
x = S.data[S.top--];
return true;
}
//括号匹配
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;
//栈不为空的操作
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(){
SqStack S;
InitStack(S);
char str[6] = {'{','}','[',']','(',')'};
int length = sizeof(str)/sizeof(str[0]);
if(bracketCheck(S,str,length)){
printf("0yes");
}else{
printf("0no");
}
printf("\n");
char str1[8] = {'{','(','(',')',')','[',']','}'};
int length1 = sizeof(str1)/sizeof(str1[0]);
if(bracketCheck(S,str1,length1)){
printf("1yes");
}else{
printf("1no");
}
printf("\n");
char str2[8] = {'{','(','(',')',']','[',']','}'};
int length2 = sizeof(str2)/sizeof(str2[0]);
if(bracketCheck(S,str2,length2)){
printf("2yes");
}else{
printf("2no");
}
printf("\n");
char str3[8] = {'{','(','(',')',')',']','(',')'};
int length3 = sizeof(str3)/sizeof(str3[0]);
if(bracketCheck(S,str3,length3)){
printf("3yes");
}else{
printf("3no");
}
printf("\n");
char str4[8] = {'{','{','(',')',')','[',']','}'};
int length4 = sizeof(str4)/sizeof(str4[0]);
if(bracketCheck(S,str4,length4)){
printf("4yes");
}else{
printf("4no");
}
}