c语言表达式括号里面三个式子,假设一个数学算法中包括圆括号(),方括号[],花括号{}三种类型,编写表达式的括号是否配对...

头文件:函数的声明

#include #include #include #include typedef char ElemType;

typedef struct node

{

ElemType data;

struct node *next;

}LStackNode,*LinkStack;

void InitStack(LinkStack *top);//将链栈初始化

int StackEmpty(LinkStack top);//判断链栈是否为空

int GetTop(LinkStack top,ElemType *e);//取栈顶元素

int PushStack(LinkStack top,ElemType e);//进栈操作

int PopStack(LinkStack top,ElemType *e);//出栈操作

int StackLength(LinkStack top);//求表长操作

void DestroyStack(LinkStack top);//销毁链表

int Match(ElemType e,ElemType ch);//判断括号

函数的定义

#include "括号配对.h"

void InitStack(LinkStack *top)//将链栈初始化

{

if((*top = (LinkStack)malloc(sizeof(LStackNode)))== NULL)

{

exit(-1);

}

(*top)->next = NULL;

}

int StackEmpty(LinkStack top)//判断链栈是否为空

{

if(top->next == NULL)

{

return 1;

}

else

{

return 0;

}

}

int GetTop(LinkStack top,ElemType *e)//取栈顶元素

{

LStackNode *p;

p = top->next ;

if(!p)

{

printf("栈已空!");

return 0;

}

*e = p->data ;

return 1;

}

int PushStack(LinkStack top,ElemType e)//进栈操作

{

LStackNode *p;

if((p = (LinkStack)malloc(sizeof(LStackNode))) == NULL)

{

printf("内存分配失败!");

return 0;

}

p->data = e;

p->next = top->next;

top->next = p;

return 1;

}

int PopStack(LinkStack top,ElemType *e)//出栈操作

{

LStackNode *p;

p = top->next ;

if(!p)

{

printf("栈已空!");

return 0;

}

top->next = p->next ;

*e = p->data ;

free(p);

return 1;

}

int StackLength(LinkStack top)//求表长操作

{

LStackNode *p;

int count = 0;

p = top;

while(p->next != NULL)

{

p = p->next ;

count++;

}

return count;

}

void DestroyStack(LinkStack top)//销毁链表

{

LStackNode *p,*q;

p = top;

while(!p)

{

q = p;

p = p->next ;

free(q);

}

}

int Match(ElemType e,ElemType ch)

{

if(e == '('&&ch == ')')

{

return 1;

}

else if(e == '['&&ch == ']')

{

return 1;

}

else if(e == '{'&&ch == '}')

{

return 1;

}

else

{

return 0;

}

}

函数的应用

#include "括号配对.h"

int main(void)

{

LinkStack S;

char *p;

ElemType e;

ElemType ch[60];

InitStack(&S);

printf("请输入其请输入带括号的表达式('()','[]','{}').\n");

gets(ch);

p = ch;

while(*p)

{

switch(*p)

{

case '(':

case '[':

case '{':

PushStack(S,*p++);

break;

case ')':

case ']':

case '}':

if(StackEmpty(S))

{

printf("缺少左括号.\n");

return 0;

}

else

{

GetTop(S,&e);

if(Match(e,*p))

{

PopStack(S,&e);

}

else

{

printf("左右括号不匹配!\n");

return 0;

}

}

default:

p++;

}

}

if(StackEmpty(S))

{

printf("括号匹配!\n");

}

else

{

printf("缺少右括号!\n");

}

return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值