数据结构实验之栈四:括号匹配
发布日期:2021-05-09 04:13:39 浏览次数:18 分类:博客文章

本文共 1880 字,大约阅读时间需要 6 分钟。

数据结构实验之栈四:括号匹配

Time Limit: 1000MS Memory limit: 65536K

题目描述

 给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

 

输入

 输入数据有多组,处理到文件结束。

 

输出

 如果匹配就输出“yes”,不匹配输出“no”

 

示例输入

sin(20+10){[}]

示例输出

yes

no

常规解法:

注意,此处建链栈方法必须是这样的。

1 #include
2 #include
3 #include
4 typedef char elemtype; 5 typedef struct node 6 { 7 char data; 8 struct node *next; 9 }stack;10 stack *top;11 void push(elemtype n)//进栈12 {13 stack *p;14 p=(stack *)malloc(sizeof(stack));15 p->data=n;16 p->next=top->next;17 top->next=p;18 }19 void pop()//出栈20 {21 stack *q;22 q=top->next;23 top->next=q->next;24 free(q);//释放内存25 }26 char gettop()//取栈顶元素27 {28 return top->next->data;29 }30 void judge(char a[])31 {32 int i,tag=0,len=strlen(a);33 for(i=0;i
next==NULL)//有了右半个括号,但是没有左半个括号的情况43 {44 printf("no\n");45 break;46 }47 if(a[i]-gettop()==1||a[i]-gettop()==2)//判断是否匹配48 pop(); //出栈49 else50 {51 printf("no\n");52 break;53 }54 }55 if(i==len)//如果没有遍历到头,此语句不执行56 {57 if(top->next==NULL)58 printf("yes\n");59 else printf("no\n");60 }61 top->next=NULL;//置栈空62 }63 int main()64 {65 top=(stack *)malloc(sizeof(stack));//申请头节点空间66 top->next=NULL;//头节点指向空67 char a[100];68 while(gets(a)!=NULL)69 {70 judge(a);71 }72 return 0;73 }
View Code

数组模拟方法:

1 #include 
2 #include
3 #include
4 #define MAXN 200 5 int st[MAXN]; 6 int main(){ 7 int top, i, len, flag; 8 char s[100]; 9 while(gets(s)){10 len = strlen(s);11 top = 0; flag = 1;12 for(i=0; i
View Code

 

上一篇:数据结构实验之栈四:后缀式求值
下一篇:数据结构实验之栈二:一般算术表达式转换成后缀式

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年04月17日 10时03分00秒