数据结构作业
2015-11-20 23:39
549 查看
迷宫问题,还非得用一下栈T_T
View Code
#include <iostream> #include <cstdio> #include <cstring> #include <map> using namespace std; const int Max=1000; class stack { private: int a[Max]; int top; public: stack() {top=-1;}; ~stack() {}; bool is_empty() {return top==-1?1:0;}; bool push(int x) {a[++top]=x;}; bool pop(); int gettop() {return a[top];}; }; bool stack::pop() { if(!is_empty()) { top--; return 1; } return 0; } class stackch { private: char a[Max]; int top; public: stackch() {top=-1;}; ~stackch() {}; bool is_empty() {return top==-1?1:0;}; bool push(int x) {a[++top]=x;}; bool pop(); char gettop() {return a[top];}; }; bool stackch::pop() { if(!is_empty()) { top--; return 1; } return 0; } stack num; stackch ch; char str[Max]; char s,st; int t; int len,pos=0; map<char,int> sign; void init() { sign.insert(pair<char,int>('#',0)); sign.insert(pair<char,int>(')',1)); sign.insert(pair<char,int>('+',2)); sign.insert(pair<char,int>('-',2)); sign.insert(pair<char,int>('*',3)); sign.insert(pair<char,int>('/',3)); sign.insert(pair<char,int>('(',4)); } void Operator(char p) { int n1=num.gettop(); num.pop(); int n2=num.gettop(); num.pop(); //cout<<n1<<n2<<p<<endl; switch(p) { case '*':num.push(n1*n2);break; case '/':num.push(n2/n1);break; case '+':num.push(n2+n1);break; case '-':num.push(n2-n1);break; } } int main() { init(); ch.push('#'); num.push(0); cin>>str; len=strlen(str); while(pos<len) { int n=0; bool flag=0; while(str[pos]<='9'&&str[pos]>='0') { int ch=str[pos]-'0'; n=n*10+ch; pos++; flag=1; } if(flag) {num.push(n);continue;} s=str[pos]; st=ch.gettop(); if((st=='('&&s==')')||(st=='#'&&s=='#')) {ch.pop();pos++;continue;} if(st=='(') {ch.push(s);pos++;continue;} if(sign[st]>=sign[s]) {Operator(st);ch.pop();continue;} ch.push(s); pos++; } cout<<num.gettop()<<endl; }
View Code
相关文章推荐
- 常见数据结构和常见算法
- heheda练数据结构
- leetcode之Maximum Depth of Binary Tree
- 数据结构(二)
- 数据结构与算法(2)--数组和typedef的运用
- 大话数据结构-程杰著 数据结构树的学习(部分)
- 旭说数据结构之二叉查找树
- 数据结构实验之串一:KMP简单应用
- 数据结构 — 图之邻接表存储创建和深度优先遍历
- 封装TableView有可能用到的数据结构和UITableViewCell的一个继承类
- 最小生成树——Prim(普利姆)算法
- 找到一个数的所有字典序即字符串的全排列
- 最小生成树基础
- 二叉排序树和堆的区别
- 第十周--数据结构--用二叉树遍历思想解决问题
- 数据结构之二叉树递归操作
- leetcode之Basic Calculator II
- 数据结构之哈希表
- 数据结构(Java)——查找和排序(4)
- 【数据结构与算法分析】2.4 求最大子序列和