数据结构 ---- 栈的应用

在此section中,我们学习了对于栈这一数据结构进行了应用,这一运用利用了线性表中最有优势的一点----容易排序,此代码将不同种的括号分到了不同的格子中,然后根据线性表的顺序进行验证,容易验证出其算式中的括号是否正确,有助于帮助我们更好的运算。

此应用有助于帮我们更好的体会其价值,帮助我们去更好的运用,提高主观能动性,同时有利于后期自己去设计代码。

在老师的代码中,我发现了,无论是正确与否,输出的数据都是一个数字:1或0,所以对于真实的代码测试过程中,它的可读性没有那么的高,所以我就给它的测试区域做了一些小小的改动,帮助我们更好的读取正确与否,提高代码的可操作性。

同时对于老师的代码是由bug的,在backerMatching函数中的末尾,无论它读取的字符是不是‘#’,返回的永远是true,所以我就做了一点小改动。

下面是我代码:

核心函数:

bool 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 brackerMatchingTest()
{
	char* tempExpression = "[2 + (1 - 3)] * 4";
	bool tempMatch = bracketMatching(tempExpression, 17);
	printf("Is the expression '%s' bracket matching?\r\n", tempExpression, tempMatch);
	if(tempMatch == TRUE)
	{
		printf("TRUE\r\n");
	}
	else
	{
		printf("FALSE\r\n");
	} 


	tempExpression = "( )  )";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching?\r\n", tempExpression, tempMatch);
	if(tempMatch == TRUE)
	{
		printf("TRUE\r\n");
	}
	else
	{
		printf("FALSE\r\n");
	}

	tempExpression = "()()(())";
	tempMatch = bracketMatching(tempExpression, 8);
	printf("Is the expression '%s' bracket matching?\r\n", tempExpression, tempMatch);
	if(tempMatch == TRUE)
	{
		printf("TRUE\r\n");
	}
	else
	{
		printf("FALSE\r\n");
	}

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

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

测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值