栈——括号匹配

//题目描述:输入一串字符串,仅含'(',')','[',']','{','}'六种字符,不含空格,且字符串以换行符结束,判断该字符串是否匹配。

//顺序栈
#include <stdio.h>
#include <stdlib.h>
#define STACK_CHAR_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10	//存储空间分配增量
typedef char SElemType;
typedef struct SqStack
{
	SElemType *base;
	SElemType *top;
	int stacksize; //当前存储空间容量
}SqStack;
void InitStack(SqStack &S) //建栈初始化
{
	S.base=(SElemType *)malloc(STACK_CHAR_SIZE*sizeof(SElemType)); //分配空间,初始化操作
	if(!S.base) exit(0);
	S.top=S.base;
	S.stacksize=STACK_CHAR_SIZE;
}
int StackEmpty(SqStack &S) //判断栈是否为空栈
{
	if(S.top==S.base) 
		return 1;
	else
		return 0;
}
void ClearStack(SqStack &S) //销毁栈
{
	S.base=S.top=NULL;
	S.stacksize=0;
}
void push(SqStack &S,SElemType e)	//进栈
{
	if(S.top-S.base>=S.stacksize)
	{
		S.base=(SElemType *)realloc(S.base,(STACK_CHAR_SIZE+STACKINCREMENT)*sizeof(SElemType)); //扩充栈空间
		S.top=S.base+S.stacksize;
		S.stacksize+=STACKINCREMENT;
	}
	*S.top++=e;
}
void pop(SqStack &S,SElemType &e) //出栈
{
	if(S.top==S.base) exit(0);
	e=*--S.top;
}
void GetTop(SqStack &S,SElemType &e) //取栈顶元素
{
	if(S.top==S.base) exit(0);
	e=*(S.top-1);
}
int compare(SElemType a,SElemType b) //括号匹配
{
	int key=0;
	if(a=='(')
	{
		if(b==')') key=1;
	}
	else if(a=='[')
	{
		if(b==']') key=1;
	}
	else if(a=='{')
	{
		if(b=='}') key=1;
	}
	return key;
}
int main()
{
	SqStack S;
	char ch,e;
	while(1)
	{
		InitStack(S);
		ch=getchar();
		while(ch!='\n')
		{
			if(ch=='(' || ch=='[' || ch=='{')
				push(S,ch);
			else
			{
				if(StackEmpty(S))
					push(S,ch);
				else
				{
					GetTop(S,e);
					if(compare(e,ch)) //e为栈顶元素,ch为当前输入元素,当栈顶括号与当前括号匹配时,就出栈
						pop(S,e);
					else
						push(S,ch);
				}
			}
			ch=getchar();
		}
		if(StackEmpty(S))
			printf("匹配\n");
		else
			printf("不匹配\n");
		ClearStack(S);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值