用栈实现括号匹配的算法

来源:互联网 发布:弓箭在淘宝上买几元 编辑:程序博客网 时间:2024/06/07 13:56

要求:

用栈的基本操作实现括号匹配算法,要求至少包括两种类型的括号。

下面的代码是我的一些思路,并不算最优的,大家学习就好啦

#include<stdio.h>#include<stdlib.h>#define MAX 5//初始创建栈的容量#define ADD 5//栈满时新增的容量typedef char ElemType;typedef struct{ElemType *base;//栈底ElemType *top;//栈顶int max;//栈的容量}sqStack;initStack(sqStack *s)//创建一个容量为 MAX 的空栈{s->base = (ElemType *)malloc(MAX * sizeof(ElemType));if (!s->base){exit(0);}s->top = s->base;s->max = MAX;}Push(sqStack *s, ElemType e)//进栈{if (s->top - s->base >= s->max){s->base = (ElemType *)realloc(s->base, (s->max = ADD) * sizeof(ElemType)); //当栈满时申请 ADD 个空间if (!s->base)exit(0);s->top = s->base + s->max;s->max = s->max = ADD;}*(s->top) = e;s->top++;}Pop(sqStack *s, ElemType *e)//出栈{if (s->top == s->base)return 0;else{*e = *--(s->top);return 1;}}int StackLen(sqStack s)//计算栈的容量{return (s.top - s.base);}int main(){sqStack p;ElemType q;initStack(&p);int count = 1;printf("输入括号进行判断,以#结束,支持“()” “<>” “{} ”\n");while ((q = getchar())  != '#'){if ('(' == q){Push(&p, q);count = StackLen(p);//进栈一次计数一次}else if ((q == ')') && (--(p).top == '(')){if (count)//出栈前判断栈是否为空Pop(&p, &q);}else if ('{' == q){Push(&p, q);count = StackLen(p);}else if ((q == '}') && (--(p).top == '{')){if (count)Pop(&p, &q);}else if ('[' == q){Push(&p, q);count = StackLen(p);}else if ((q == ']') && (--(p).top == '[')){if (count)Pop(&p, &q);}else if ('<' == q){Push(&p, q);count = StackLen(p);}else if ((q == '>') && (--(p).top == '<')){if (count)Pop(&p, &q);}}count = StackLen(p);//循环结束后再判断栈是否还有元素if (!count)//flag为0时代表已经全部匹配出栈printf("yes\n");elseprintf("no\n");return 0;}

注:代码仅供学习使用

0 0
原创粉丝点击