C++栈的运用,判断大、中、小括号的合法性()

缘由

#define MAX_STACK_SIZE 100 //宏定义全局变量
typedef  struct SqStack
{
	char data; struct SqStack *next;
}SqStack;//链元素
typedef  struct Stack
{
	struct SqStack *base; //栈底指针
	struct SqStack *top;  //栈顶指针
}Stack;//栈 OK
Stack S;
typedef struct node{ char key; }element_tr;//运算符栈
typedef struct Node{ int data; }element_nd;//操作数元素
void creatstack(Stack &S)
{
	S.top = S.base = NULL;
}//建立初始化链栈
void push(Stack &S, char e, int &Aj)
{
	SqStack* Q;
	Q = (SqStack*)malloc(sizeof(SqStack));
	Q->next = S.top;
	S.top = Q;
	S.top->data = e;
	++Aj;
}//左括号入栈
char Pop(Stack &S)
{
	char e;
	SqStack *q;
	e = S.top->data;
	q = S.top->next;
	free(S.top);
	S.top = q;
	return e;
}//括号出栈
int check(int &Aj)
{
	char strig[100]{};
	int A = 1;
	int w = 0;
	char sh, ch, *st, *stt;
	printf("请输入算术表达式并以'='结束输入:\n");
	scanf_s("%s", &strig,100);
	getchar();
	st = stt = strig;
	ch = *st;
	sh = *++stt;
	while (ch != '=')
	{
		if (w == 0)
		if (ch == ']' || ch == '}' || ch == ')')
		{
			A = -1; Aj = 1;
		}
		if ((ch == '[' || ch == '(' || ch == '{') && (sh == '='))
		{
			A = -1;
			Aj++;
			break;
		}
		if (A == -1) break; w++;
		if (ch == '[' || ch == '(' || ch == '{' || ch == ']' || ch == '}' || ch == ')')//判断是否满足入栈和出栈条件
			switch (ch)
		{
			case '[': {push(S, ch, Aj); break; }
			case '{': {push(S, ch, Aj); break; }
			case '(': {push(S, ch, Aj); break; }//左括号入栈
			case ']': if (Pop(S) != '['){ A = -1; Aj++; break; }
					  else
					  {
						  Aj++; break;
					  }
			case ')': if (Pop(S) != '('){ A = -1; Aj++; break; }
					  else
					  {
						  Aj++; break;
					  }case '}':
						  if (Pop(S) != '{')
						  {
							  A = -1; Aj++; break;
						  }
						  else
						  {
							  Aj++; break;
						  }
		}//出栈并与字符ch匹配比较
		ch = *(++st);
		sh = *(++stt);
		if ((S.base == S.top) && (ch == ']' || ch == '}' || ch == ')'))
		{
			A = -1; Aj++;
		}
		if (A == -1)break;
	}
	if (S.base != S.top)
		A = -1;
	return A;
}
void 栈的运用,判断大、中、小括号的合法性()
{//缘由https://ask.csdn.net/questions/1057038
	int st = 0, Aj = 0;
	char w = 'y';
	printf("\n*******括号配对判别********\n");
LL:
	while (w != 'n'&&w != 'N')
	{
		creatstack(S);
		st = check(Aj);
		if (st == -1)
		{
			printf("表达式中第%d个括号与对应括号不匹配,请重新输入\n", Aj);
			goto LL;
		}
		else
		{
			printf("表达式中括号匹配\n");
		}
		printf("继续请输入'y',退出请输入'n'!\n");
		w = getchar();
		getchar();
	}
	printf("----------感谢使用!----------\n");
}

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值