数据结构-栈的应用-算术表达式小括号匹配

数据结构高分笔记,第3章《栈》的第一个例题,题目要求检测算术表达式中小括号匹配是否合法。感觉自己的算法还是有点弱智啊,这么多判断好像很low逼!!!!


#include <stdio.h>
#include <string.h>
#define max 5

typedef struct 
{
	char exp[max];
	int top;
}sqstack;

void main()
{
	sqstack st;
	int i=0;
	int counter1=0;
	st.top=-1;
	char *s ="(sa(s(d))f)(";//测试数据入口
	printf("\n");
	while (*s!=NULL)
	{
		if ( *s==')'&&st.exp[st.top]!='(' )//右括号前无左括号,匹配失败,提示
		{
			st.top++;
			st.exp[st.top]=*s;
			break;
		}
		if ( *s==')'&&st.exp[st.top]=='(' )//与前一个左括号匹配成功,出栈
		{
			st.exp[st.top]='0';
			st.top--;
			*++s;
			continue;
		}
		
		if ( *s=='(' )//左括号为起始括号,始终可以入栈
		{
			st.top++;
			st.exp[st.top]=*s;
			*++s;
			continue;
		}
		if ( *s!='('&&*s!=')' )//跳过普通字符
		{
			*++s;
		}
	}
	if ( st.exp[st.top]=='('||st.exp[st.top]==')' )
	{
		printf("error\n");
	}
	else printf("no error\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值