数据结构实验之栈四:括号匹配
2015-08-13 17:08
447 查看
数据结构实验之栈四:括号匹配
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。输入
输入数据有多组,处理到文件结束。输出
如果匹配就输出“yes”,不匹配输出“no”示例输入
sin(20+10) {[}]
示例输出
yesno
链表的方法,较为复杂。需要建立链栈,将数组代替栈的方法换为了线性表
#include <stdio.h> #include <stdlib.h> #include <string.h> #include<iostream> using namespace std; typedef char anytype; struct stacks { struct node //链栈 { anytype data; struct node *next; }*head; stacks() //构造链 { head=new node; head->next=NULL; } bool empty() //判断是否为空栈 { if(head->next) return false; return true; } void push(anytype n) //入栈 { struct node *p; p=new node; p->data=n; p->next=head->next; head->next=p; } void pop() //出栈 { struct node *p; p=head->next; if(p) { head->next=p->next; free(p); } } anytype top() //查询栈顶元素 { if(!empty()) return head->next->data; return 0; } }; bool isbrackets(char ch) //判断输入的是否为括号 { if(ch==')'||ch=='('||ch==']'||ch=='['||ch==')'||ch=='(') return true; return false; } bool tocheck(stacks &s,char ch) // 检查是否与栈顶括号匹配 { if(s.empty()) { return false; } switch(ch) { case ')': if(s.top()=='(') return true; return false; case ']': if(s.top()=='[') return true; return false; case '}': if(s.top()=='{') return true; return false; default : return false; } } int main() { ios::sync_with_stdio(false); string str; while(getline(cin,str,'\n')) { stacks s; bool mark=true; int len=str.length(); for(int i=0; i<len; i++) { if(isbrackets(str[i])) { if(str[i]=='('||str[i]=='['||str[i]=='{') //左括号入栈 s.push(str[i]); else if(tocheck(s,str[i])) //右括号如果与栈顶匹配则弹出栈顶左括号 s.pop(); else { mark=false; //标记括号不匹配 break; } } } if(s.empty()&&mark) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }数组(栈)的方法,简单明白
#include <iostream> #include <cstdio> #include <algorithm> #include <ctype.h> #include <cstring> #include <stack> using namespace std; int main() { char f[60],t; int i; while(gets(f)!=NULL) { stack <char> s; int v=1; for(i=0;i<strlen(f);i++) { if(f[i]=='('||f[i]=='['||f[i]=='{') s.push(f[i]); if(f[i]==')'||f[i]==']'||f[i]=='}') { if(s.empty()) {v=0;break;} else { t=s.top();s.pop(); if(f[i]==')') if(t!='(') {v=0;break;} if(f[i]==']') if(t!='[') {v=0;break;} if(f[i]=='}') if(t!='{') {v=0;break;} } } } if(!s.empty()) v=0; if(v) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }
相关文章推荐
- 数据结构实验之栈三:后缀式求值
- 数据结构
- [数据结构]堆
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈一:进制转换
- 数据结构--画画--最小生成树(Prim算法)
- 数据结构-栈2(学习笔记)
- 数据结构-栈1(学习笔记)
- 数据结构—队列
- AVL树的构造实现
- 数据结构预算法C++描述( 一)引论
- 基本数据结构:树(tree)
- 数据结构笔试题(单选)
- 微软公司等数据结构+算法面试100题(第1-100题)全部出炉
- 数据结构之二叉树详解
- 数据结构日常笔记总结
- 图论-BFS解无权有向图最短路径距离
- H264数据结构
- nginx源码分析2———基础数据结构五(ngx_hash_wildcard_t)
- 中国大学MOOC-陈越、何钦铭-数据结构基础习题集 00-自测1. 打印沙漏(20)