数据结构3.2栈的应用——括号匹配

本文介绍了如何使用栈来解决括号匹配的问题,通过压栈、弹栈操作检查括号的正确性。提供了一个`bracketMatching`函数实现,以及测试用例,展示了对于有效和无效括号表达式的判断。通过这种方法,可以高效地处理复杂的括号逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

还在为20,30个括号之间的逻辑关系无法理清而烦恼?巧妙运用栈,解放双手,解放双眼!

首先,进行栈的定义,压栈,弹栈,打印,压栈、弹栈测试代码实现,在此不做展示,详情可见上期:数据结构3.1栈的基本操作:http://t.csdn.cn/kPlqW

 

接下来,对重点代码进行实现

void bracketMatching(char* paraString, int paraLength) {

	CharStackPtr tempStack = charStackInit();
	push(tempStack, '#');
	char tempChar, tempPopedChar;


	for (int i = 0; i < paraLength; i++) {
		tempChar = paraString[i];

		switch (tempChar) {
		case '(':
		case '[':
		case '{':
			push(tempStack, tempChar);
			break;
		case ')':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '(') {
				return false;
			}
			break;
		case ']':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '[') {
				return false;
			}
			break;
		case '}':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '{') {
				return false;
			}
			break;
		default:

			break;
		}
	}

	tempPopedChar = pop(tempStack);
	if (tempPopedChar != '#') {
		return false;
	}

	return true;
}

测试函数

void bracketMatchingTest() {
	char* tempExpression = "[2 + (1 - 3)] * 4";
	bool tempMatch = bracketMatching(tempExpression, 17);
	printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);


	tempExpression = "( )  )";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);

	tempExpression = "()()(())";
	tempMatch = bracketMatching(tempExpression, 8);
	printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);

	tempExpression = "({}[])";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);


	tempExpression = ")(";
	tempMatch = bracketMatching(tempExpression, 2);
	printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
}

主函数

int main() {
	pushPopTest();
	bracketMatchingTest();
}

解决升级问题的时候还是得从最基础的进行,最基本的需要理清弹栈,压栈顺序,在进行系统的敲代码。今天又是纯纯代码人了,希望代码对大家有帮助,大家点点关注小红心哦~~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值