括号匹配问题 栈c语言实验报告,用堆栈解决括号匹配问题(C语言)

#include

#include

int main()

{

void BracketMatch();

BracketMatch();

}

typedef char ElemType;

typedef struct Stack

{

int top;

int MaxSize;

ElemType *stack;

}Stack;

void Creat(Stack*s , int m)

{

if(m<0) { printf("%d is negtive!",m);

return;

}

s->top=-1;

s->MaxSize=m;

s->stack=(ElemType*)malloc(sizeof(ElemType)*m);

}//Creat a stack

void Push(Stack *s, ElemType data)

{

if(s->top==s->MaxSize-1)

{

printf("The stack is full!");

return;

}

s->top++;

s->stack[s->top]=data;

}//Push data in the stack s

ElemType Pop(Stack *s)

{

ElemType temp;

if( s->top

{

printf("The stack is NULL!");

return;

}

temp=s->stack[s->top];

s->top--;

return temp;

}//Pop the top element of the stack

void BracketMatch() {  int n=20;  int i=0;  char str[n];  char ch;  printf("请输入一个算术表达式(%d字符以内)\n",n);  scanf("%s",str);  Stack *s=(Stack*)malloc(sizeof(Stack));  Creat(s,n);//creat a stack of n elements  while(str[i]!='\0')  {   if(str[i]=='(' ||str[i]=='{' ||str[i]=='[' )    Push(s,str[i]);   if(str[i]==')')   {    ch=Pop(s);    if(ch!='(')    {  printf("Match failure!\n");return; }   }   if(str[i]==']')   {    ch=Pop(s);    if(ch!='[')    {  printf("Match failure!\n");return; }   }   if(str[i]=='}')   {    ch=Pop(s);    if(ch!='{')    {  printf("Match failure!\n");return; }   }   i++;  }  if(s->top==-1)   //最后堆栈有无元素判断   printf("Match Successfully!\n");  else   printf("Match failure!\n");  }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值