栈:返回括号匹配问题中失配时栈的深度

本题要求在栈的存储结构下设计算法,假设一个算术表达式中包含”(、)、{、}、[、]“三

种类型的括弧,借助栈结构设计一个算法用于判别表达式中括弧是否正确配对。

如果是不匹配的返回不匹配时栈中元素的个数(栈的深度),若果是匹配的返回0(实际也为栈的深度);

#include<stdio.h>
#include<string.h>
#define MaxSize 50
typedef struct {
	char data[MaxSize];
	int top;
} SeqStack;
void InitStack(SeqStack *S) {
	S->top=-1;
}
int StackEmpty(SeqStack *S) {
	if(S->top==-1)
		return 1;
	else
		return 0;
}
int Push(SeqStack *S,char x) {
	if(S->top==MaxSize-1)
		return 0;
	S->data[++S->top]=x;
	return 1;
}
int Pop(SeqStack *S,char *x) {
	if(S->top==-1)
		return 0;
	*x=S->data[S->top--];
	return 1;
}
int GetTop(SeqStack *S,char *x) {
	if(S->top==-1)
		return 0;
	*x=S->data[S->top];
	return *x;
}
int StackLength(SeqStack *S) {
	return S->top+1;

}
int judge(SeqStack *S,char str[]) {
	char x;
	for(int i=0; i<strlen(str); i++) {
		while((str[i]=='(')||(str[i]=='{')||(str[i]=='[')) {
			Push(S,str[i]);
			i++;
		} 
		if((GetTop(S,&x)=='('&&str[i]!=')')||(GetTop(S,&x)=='['&&str[i]!=']')||(GetTop(S,&x)=='{'&&str[i]!='}')) {
	
				break;
			}
			if((GetTop(S,&x)=='('&&str[i]==')')||(GetTop(S,&x)=='['&&str[i]==']')||(GetTop(S,&x)=='{'&&str[i]=='}')) {
				Pop(S,&x);
			}
	}

	return StackLength(S);
}

int main() {
	int y;
	SeqStack S;
	char str[100];
	InitStack(&S);
	gets(str);
	y=judge(&S,str);
	if( y== 0)
		printf("%d,True!",y);
	else
		printf("%d,False!",y);
	return 1;
}

 

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扎心小指针0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值