c语言栈训练题目:括号匹配
基本思路:
- 当前字符不是括号,不做处理;
- 当前字符是左括号,则进栈;
- 当前字符是右括号:若栈空,则表明该“右括号”多余,不匹 配,结束;否则和栈顶元素比较,若不匹配,结束;若和栈顶匹 配,则栈顶元素出栈;
- 当前字符是结束符时,若栈空,则匹配正确;否则表明“左括 号”多余,不匹配,结束。
- 读取下一字符,重复以上步骤
以下是代码区:
#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");
}
}