用栈实现括号匹配(c语言)

主要思想:
用栈实现括号匹配:依次扫描所有字符,遇到左括号则入栈,遇到右括号则弹出栈顶元素检查是否匹配。

匹配失败情况:
1、左括号单身
2、右括号单身
3、左右括号不匹配

代码:

//用顺序栈实现括号匹配
#include<stdio.h>
#define MAXSIZE 10
typedef int bool;
#define true 1
#define false 0
typedef struct{
  char data[MAXSIZE]; //静态数组存放栈中元素
  int top;  //当前栈顶元素
}SqStack;

bool bracketMatching(char str[],int length);
void initStack(SqStack *S);
bool stackEmpty(SqStack S);
bool push(SqStack *S,char e);
bool pop(SqStack *S,char *e);
bool getTop(SqStack S,char *e);
void printStack(SqStack S);

/*
  用栈实现括号匹配:
  依次扫描所有字符,遇到左括号则入栈,遇到右括号则弹出栈顶元素检查是否匹配。

  匹配失败情况:
  1、左括号单身
  2、右括号单身
  3、左右括号不匹配
*/
bool bracketMatching(char str[],int length){
  SqStack S;
  initStack(&S);
  for(int i=0;i<length;i++){
    //扫描左括号,入栈
    if(str[i]=='('||str[i]=='{'||str[i]=='['){
        push(&S,str[i]);
    }else{
        //扫描遇到右括号,且当前栈空,则匹配失败
        if(stackEmpty(S)){
            return false;
        }
        char e;
        pop(&S,&e);
        //左右括号不匹配,则匹配失败
        if(str[i]==')'&&e!='('){
            return false;
        }
        if(str[i]=='}'&&e!='{'){
            return false;
        }
        if(str[i]==']'&&e!='['){
            return false;
        }
    }
  }
  //考虑左括号是不是为0
  return stackEmpty(S);
}

void initStack(SqStack *S){
  S->top=-1;
}

bool stackEmpty(SqStack S){
  if(S.top>=0){
    return false;
  }
  return true;
}

bool push(SqStack *S,char e){
  if(S->top==MAXSIZE-1){
    return false;
  }
  S->top=S->top+1;
  S->data[S->top]=e;
  return true;
}

bool pop(SqStack *S,char *e){
   if(S->top==-1){
    return false;
   }
   *e=S->data[S->top];
   S->top=S->top-1;
   return true;
}

bool getTop(SqStack S,char *e){
   if(S.top==-1){
    return false;
   }
   *e=S.data[S.top];
   return true;
}

void printStack(SqStack S){
   for(int i=S.top;i>=0;i--){
    printf("%c ",S.data[i]);
   }
   printf("\n");
}

int main(){
  char e;
  char str[]={'[','{','[','(',')',')','}',']'};
  int lenth=sizeof(str)/sizeof(char);
  for(int i=0;i<lenth;i++){
    printf("%c ",str[i]);
  }
  printf("\n");
  if(bracketMatching(str,lenth)){
    printf("括号匹配\n");
  }else{
    printf("括号不匹配\n");
  }
  return 0;
}

运行结果:
在这里插入图片描述

  • 16
    点赞
  • 123
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值