括号匹配问题

# include <stdio.h>
# include <stdlib.h>
# define TRUE 1
# define FALSE 0
typedef char ElementType;


typedef struct node 
{
ElementType data;
struct node *next;
}LinkStackNode, *LinkStack;


void InitStack(LinkStack top)   //初始化
{
top->next = NULL;
}
int Push(LinkStack top,ElementType e)   //进栈
{
LinkStack temp;
temp = (LinkStack)malloc(sizeof(LinkStackNode));
if (temp == NULL)
return FALSE;
temp->data = e;
temp->next = top->next;
top->next = temp;
return TRUE;
}
IsEmpty(LinkStack top)            //判断栈满
{
if (top->next == NULL)
return TRUE;
else
return FALSE;
}
void GetTop(LinkStack top,ElementType *e)  //读栈顶
{
  *e = top->next->data;
}
int Pop(LinkStack top, ElementType *e)   //出栈
{
LinkStack temp;
temp = (LinkStack)malloc(sizeof(LinkStackNode));
    temp = top->next;
if (temp == NULL)
return FALSE;
*e = temp->data;
top->next = temp->next;
free(temp);
return (TRUE);
}
int Match(char ch,ElementType e)    //判断是否匹配
{
if ((ch == '(' && e == ')') || (ch == '{' && e == '}') || (ch == '[' && e == ']'))
return TRUE;
else
return FALSE;
}


void BracketMatch(LinkStack top, char *str)    //括号匹配算法
{
char ch;
int i;
for (i = 0;str[i] != '\0'; i++)
{
switch(str[i])
{
case'(':
case'[':
case'{':
Push(top,str[i]);
break;
case')':
case']':
case'}':
if (IsEmpty(top))
{
printf("\n右括号多余!");
return;
}
else
{
GetTop(top,&ch);
if (Match(ch,str[i]))
Pop(top,&ch);
else
{
printf("\n对应的左右括号不同类!");
return ;
}
}//else
} //switch


} //for
if (IsEmpty(top))
printf("\n括号匹配!");
else
printf("\n左括号多余!");
}
int main(void)
{
LinkStack top;
char str[100];
    top = (LinkStack)malloc(sizeof(LinkStackNode));
InitStack(top);
printf("请输入一组括号\n");
scanf("%s",&str);
BracketMatch(top,str);
printf("\n");
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值