边进边匹配
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 20
typedef struct
{
char data[MaxSize];
int top;
}LNode;
/*初始化栈*/
void Init(LNode *S)
{
S->top = -1;
}
/*判断是否为空*/
bool JudgeEmpty(LNode *S)
{
if(S->top == -1)return true;
else return false;
}
/*判断是否栈满*/
bool JudgeFull(LNode *S)
{
if(S->top >= 20)return true;
else return false;
}
/*入栈*/
void EnStack(LNode *S,char ch)
{
S->data[++S->top] = ch;
}
/*出栈*/
int DeStack(LNode *S)
{
return S->data[S->top--];
}
/*判断是否匹配*/
bool JudgeAccord(char ch1,char ch2)
{
if(ch1 == '[' && ch2 == ']')return true;
else if(ch1 == '(' && ch2 == ')')return true;
else return false;
}
int main(int argc, char const *argv[]) {
LNode S;
char ch;
Init(&S);
printf("请输入括号 * 结束:");
scanf("%c",&ch);
while (ch != '*' && !JudgeFull(&S)) {
//如果栈为空 直接入栈
if(JudgeEmpty(&S))EnStack(&S,ch);
else if(JudgeAccord(S.data[S.top],ch))//如果栈顶与输入括号相匹配 则 栈顶出栈
{
DeStack(&S);
}
else//不匹配则 入栈
{
EnStack(&S,ch);
}
scanf("%c",&ch);
}
//最终栈内无剩余元素则表明匹配成功
if(JudgeEmpty(&S))printf("Yes\n");
else printf("No\n");
return 0;
}