数据结构之括号匹配问题

输入一个表达式,表达式中包括三种括号“()”、“[]”和“{}”,判断该表达式的括号是否匹配。

没达到输出那个括号出错的目的,不过也能判断是否正确了。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef struct SqStack{
	char *base;
	int top;
	int stacksize;
}SqStack;

void InitStack(SqStack &S)
{//构造一个空的栈 
	S.base=(char *)malloc(STACK_INIT_SIZE*sizeof(SqStack));
	if(!S.base)
		exit(0);
	S.top=0;
	S.stacksize=STACK_INIT_SIZE;
}

int Push(SqStack &S,char e)
{//元素进栈 
	if(S.top>=S.stacksize-1)
	{
		S.base=(char *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SqStack));
	}
	S.base[S.top]=e;
	S.top++;
	if(S.base[S.top-1]==e)
		return 1;
	else 
		return 0;
}

int pop(SqStack &S,char &e)
{//元素出栈 
	if(S.top >= 1)
	{
		S.top--;
		e=S.base[S.top];
		return 1;
	}
	
	return 0;
}

int judge(SqStack &S,int cnt,char *a)
{
	char tt;
	int n;
	
	for(int i=0;i<cnt;i++)
	{
		if(a[i] == '(' || a[i] == '[' || a[i] == '{')
		{
			Push(S,a[i]);
		}
		else
		{
			n=S.top-1;
			if(n<0)
				return 0;
			pop(S,tt);
			if( ( a[i]==')'&&tt=='(' ) || ( a[i]==']'&&tt=='[' ) || ( a[i]=='}'&&tt=='{' ) )
			{
				
			}
			else
				return 0;
		}
	}
	if(S.top!=0)
		return 0;
		
	return 1;
}

int main()
{
	SqStack S;
	int n,cnt;
	char a[1000];
	char tmp;
		
	InitStack(S);
	printf("请输入你要判断的这些括号\n");
	gets(a);
	cnt=strlen(a);
	if(judge(S,cnt,a))
		printf("格式正确\n");
	else
		printf("格式错误\n");	
	
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值