
数据结构实验之栈四:括号匹配
View Code View Code
发布日期:2021-05-09 04:13:39
浏览次数:18
分类:博客文章
本文共 1880 字,大约阅读时间需要 6 分钟。
数据结构实验之栈四:括号匹配
Time Limit: 1000MS Memory limit: 65536K
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10){[}]
示例输出
yes
no
常规解法:
注意,此处建链栈方法必须是这样的。
1 #include2 #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 }
数组模拟方法:
1 #include2 #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
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2025年04月17日 10时03分00秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
不需要爬虫也能轻松获取 unsplash 上的图片
2019-03-06
elementUi源码解析(1)--项目结构篇
2019-03-06
Nmap扫描工具介绍
2019-03-06
算法笔记:递归、动态规划
2019-03-06
常用Windows 快捷键
2019-03-06
linux命令-压缩与打包
2019-03-06
ORACLE 11g 生产中高水位线(HWM)处理
2019-03-06
centos 6.x 编译安装 pgsql 9.6
2019-03-06
weblogic 服务器部署SSL证书
2019-03-06
oracle 11g not in 与not exists 那个高效?
2019-03-06
Linux 安装Redis 5.0(以及参数调优)
2019-03-06
html5 Game开发系列文章之 零[开篇]
2019-03-06
Golang Web入门(4):如何设计API
2019-03-06
ES6基础之——new Set
2019-03-06
玩玩小爬虫——试搭小架构
2019-03-06
Javascript之旅——第八站:说说instanceof踩了一个坑
2019-03-06