c语言栈训练题目:括号匹配

c语言栈训练题目:括号匹配

基本思路:

  1. 当前字符不是括号,不做处理;
  2. 当前字符是左括号,则进栈;
  3. 当前字符是右括号:若栈空,则表明该“右括号”多余,不匹 配,结束;否则和栈顶元素比较,若不匹配,结束;若和栈顶匹 配,则栈顶元素出栈;
  4. 当前字符是结束符时,若栈空,则匹配正确;否则表明“左括 号”多余,不匹配,结束。
  5. 读取下一字符,重复以上步骤
    以下是代码区:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 100 
typedef struct SqStack{
	char elem[MAXSIZE];
	int top;
}SqStack; //定义顺序栈

void Init(SqStack *S) //初始化建栈 
{	
	if(S==NULL)
		exit(1);
	S->top = -1;	
}
void Push(SqStack *S,char e) //进栈
{
	if(S==NULL) exit(1);
	S->top++;
	S->elem[S->top] = e;
}
int Exclude_orthers_left(char e) //判断是否是括号 是1,否0 
{
	if(e == '[' || e == '(' || e == '{')
	{
		return 1;
	}
	else 
		return 0;
}
int Exclude_orthers_right(char e) //判断是否是右括号
{
	if(e == ']' || e == ')' || e == '}')
	{
		return 1;
	}
	else
	{
		return 0;
	}
} 
void Output(SqStack *S) //输出函数 
{
	if(S->top==-1)
	{
		printf("无数据\n");
	}
	else
	{
		printf("%s",S->elem);
	}
}
void Deletetop(SqStack *S)
{
	S->top--;
}
void Judge(SqStack *S,char e)
{
	int AscL,AscR;
	AscL=S->elem[S->top];
	AscR=e;
	if(S->top==-1)
	{
		printf("%c不匹配\n",e);
		exit(1);
	}
	else if(AscL==40 && AscR==41)
	{
		Deletetop(S);
		//printf("%c匹配%c",AscL,AscR);
	}
	
	else if(AscL==91 && AscR==93)
	{
		Deletetop(S);
		//printf("%c匹配%c",AscL,AscR);
	}
	else if(AscL==123 && AscR==125)
	{
		Deletetop(S);
		//printf("%c匹配%c",AscL,AscR);
	}
	else
	{	
		printf("%c没有找到匹配括号\n",AscL);
		//Deletetop(S);
		exit(1); 
	}
}
void main()
{	
	/*
	1+a[3]*(k+2)
	(1+x)*(3+a[5]/2+a[7] //测试案例:
	*/
	SqStack S;
	Init(&S); 
	int i;
	char input[100];
	printf("输入算式:\n");
	gets(input);
	for(i=0; i<strlen(input); i++)
	{
		if(Exclude_orthers_left(input[i]))
		{
			Push(&S,input[i]);
		}
		else if(Exclude_orthers_right(input[i]))
			Judge(&S,input[i]);
	}
	if(S.top==-1)
	{
		printf("全部匹配!\n "); 
	}	
	if(S.top>-1)
	{
		for(i=0;i<=S.top;i++)
		{
			printf("%c ",S.elem[S.top]);
		}
		printf("没有找到匹配括号!\n");
	}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值