王道考研 ++++ 栈-括号匹配问题(C语言)

边进边匹配

#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;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值