栈的应用习题
来源:互联网 发布:dd linux 编辑:程序博客网 时间:2024/05/19 01:10
//中缀表达式转后缀表达式
/*特别注意 中缀表达式转为后缀表达式:当运算符优先级比栈顶运算符高时直接入运算栈,如果等于或低于栈顶运算符时将运算符栈的出栈 (转为前缀表达式时没有等于)*/#include <iostream>#include <stack>using namespace std;int main(){ string str; stack<char> opr; stack<char> open; cout << "输入一个中缀表达式:"<< endl; cin >> str; cout << "原表达式为:" << str << endl; auto i = str.begin(); while (i != str.end()) { switch (*i) { case '(': { opr.push(*i); // 入栈 ++i; break; } case '+': case '-': { if (opr.empty()) { opr.push(*i); ++i; break; } while (!opr.empty() && opr.top() != '(') { open.push( opr.top() ); // 当前运算符优先级低于操作符时 //把操作符栈内的入到数栈 opr.pop(); // 出栈 } opr.push(*i); ++i; break; } case '*': case '/': { if (opr.empty()) { opr.push(*i); ++i; break; } if ( (opr.top() == '+' || opr.top() == '-') || opr.top() =='(' ) { opr.push(*i); ++i; break; } while (!opr.empty() && (opr.top() == '/' || opr.top() == '*') ) { open.push(opr.top()); opr.pop(); } opr.push(*i); ++i; break; }/* case '/': {// while (!opr.empty() && opr.top() != '(') opr.push(*i); ++i; break; } */ case ')': { while (opr.top() != '(') { open.push(opr.top()); opr.pop(); } if (opr.top() == '(') opr.pop(); ++i; break; } default : { open.push(*i); ++i; break; } } } //opr弹出到open while (!opr.empty()) { open.push(opr.top()); opr.pop(); } cout << "操作完毕:" << endl; //显示栈: while (!open.empty()) { cout << open.top(); open.pop(); } return 0;}
//括号配对问题
#include <iostream>#include <stack>using namespace std;int main(){ string str; cout << "请输入一串只有()[]的字符" << endl; cin >> str; cout << "str 中的元素是:" << str << endl; stack<char>sta; // 注意是char类型的 auto i = str.begin(); while (i != str.end()) { if (*i == '(' || *i == '[') { sta.push(*i); i++; } else if ( *i == ')') { if (sta.empty() || sta.top() != '(') { cout << "no" << endl; return 0; } else if(sta.top() == '(') { sta.pop(); ++i; } } else if (*i == ']') { if (sta.empty() || sta.top() != '[') { cout << "no" << endl; return 0; } else if (sta.top() == '[') { sta.pop(); ++i; } } } if (sta.empty()) cout << "yes" << endl; else cout << "no" << endl; cout << "结束"; return 0;}
阅读全文
0 0
- 栈的应用习题
- 习题6 -1 Parentheses Balance uva673 简单栈的应用
- 栈的习题
- 关于栈的习题
- 栈的习题
- 栈的一些习题
- 栈和队列的应用相关习题及详解 ——数据结构
- 习题11:编写程序综合应用Directory类的主要方法。
- 关于栈的习题的解答
- 栈的习题(1),(2)。
- 栈的习题 (1)(2)
- 算法导论第2章(4) 分治法的应用 找逆序对 (习题2-4)
- 做习题的境界
- vector操作的习题
- 一个JavaScript 的习题
- 习题9.18的答案
- 习题9.18的答案
- 要做的习题
- ORA-20000:ORU-10027:buffer overflow,limit of 10000 bytes 解决方法
- 多线程的安全问题。 创建线程的两种方式区别
- Nginx动静分离实现
- java Native Method
- 2017-11-8 编辑模式
- 栈的应用习题
- 设备识别及文件查找
- 6.4
- Allegro导入网表报错
- 小波和多分辨率处理
- C++之变量及数据存储
- 用Python写Reverse TCP 后门
- IOS-UITableViewStyle设置Group、Plain问题
- NOIP 提高组取得480分以上的成绩有多难?