括号匹配

//检查一个算法表达式中的括号是否匹配,算术表达式保存于字符数组中
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20

typedef struct
{
	char data[MAXSIZE];
	int top;
}SeqStack;                                     //顺序栈类型 

void Init_SeqStack(SeqStack **q)               //顺序栈初始化
{
	*q = (SeqStack *)malloc(sizeof(SeqStack));
	(*q)->top = -1;
}

int Empty_SeqStack(SeqStack *q)                //判断栈空
{
	if (q->top == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

 void Push_SeqStack(SeqStack *q, char x)        //元素入栈
 {
	if (q->top == MAXSIZE - 1)
	{
		printf("Stack is full!\n");
	}
	else
	{
		q->top++;
		q->data[q->top] = x; 
	}
 }

 void Pop_SeqStack(SeqStack *q, char *x)         //元素出栈
 {
	 if (q->top == -1)
	 {
		printf("Error!\n");
	 }
	 else
	 {
		 *x = q->data[q->top];
		 q->top--;
	 }
 }

 void Top_SeqStack(SeqStack *q, char *x)          //取栈顶元素
 {
	if (q->top == -1)
	{
		printf("The stack is empty!\n");
	}
	else
	{
		*x = q->data[q->top];
	}
 }

 void Correct(char ex[])                          //检查算术表达式中的括号是否匹配
 {
	SeqStack *p;
	char x, *ch = &x;
	int i = 0;
	Init_SeqStack(&p);
	while (ex[i] != '\n')
	{
		if (ex[i] == '(' || ex[i] == '[' || ex[i] == '{')
		{
			Push_SeqStack(p, ex[i]);
		}
		if (ex[i] == ')' || ex[i] == ']' || ex[i] == '}')
		{
			Top_SeqStack(p, ch);
			if (ex[i] == ')' && *ch == '(')
			{
				Pop_SeqStack(p, ch);
				goto l1;
			}
			if (ex[i] == ']' && *ch == '[')
			{
				Pop_SeqStack(p, ch);
				goto l1;
			}
			if (ex[i] == '}' && *ch == '{')
			{
				Pop_SeqStack(p, ch);
				goto l1;
			}
			else
			{
				break;                             //不配对时则终止扫描
			}
		}
    l1:	i++;                                       //继续扫描下一个字符
	}

	if (!Empty_SeqStack(p))
	{           //算术表达式扫描结束或非正常结束时,若栈不为空则不配对
		printf("Error!\n");
	}
	else
	{
		printf("Right!\n");
	}
}

int main()
{
	char x[30];
	printf("Input exp:\n");                        //输入一个算术表达式
	scanf("%s", x);
	Correct(x);

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值