//检查一个算法表达式中的括号是否匹配,算术表达式保存于字符数组中
#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;
}
括号匹配
最新推荐文章于 2023-10-30 15:11:31 发布