C/C++ 使用栈实现括号匹配,函数自己实现

 王道考研-数据结构中的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");
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值