中缀符号到反波兰符号
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了中缀符号到反波兰符号相关的知识,希望对你有一定的参考价值。
The bugged version: Somehow, it prints random characters to me like [] except the spaces filled in and other accented letters when I input more parenthesis and longer input.How to use: example->
input:
3
1+2
(1+2)*(6-2)
6-7*(9*10)/8
output:
1 2 +
1 2 + 6 2 - *
6 7 - 9 10 ** 8 /
#include <iostream> #include <cctype> #include <string> #include <list> #include <stack> using namespace std; char pop(list<char> & a) //Pops the stack and returns it, I use it to append to output vector { char result = a.front(); a.pop_front(); return result; } int main() { int num; string in; cin >> num; string out; //stores outputed characters front operator stack list<char> opr; for(int zed=0; zed<num; zed++) { cin >> in; for(int i =0; i < in.length(); i++) { switch(in[i]) //Gets operator gets their precedence and pushes them into the stack(list) and //output string { case '(': opr.push_front(in[i]); break; case ')': while(opr.front()!='(' && !opr.empty()) { out.push_back(pop(opr)); } opr.pop_front(); break; case '-': if(opr.front() == '+' || '*' || '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '+': if(opr.front() == '-' || '*' || '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '*': if(opr.front() == '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '^': opr.push_front(in[i]); out.push_back(' '); break; case '/': if(opr.front() == '^' || '*' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; default: if(isdigit(in[i]) || isalpha(in[i])) //Default: if character is a digit or a letter append it to output out.push_back(in[i]); } } while(!opr.empty()) //if the stack isn't empty push the rest into the output vector { out.push_back(pop(opr)); opr.pop_front(); } out.erase(remove(out.begin(), out.end(),'('), out.end()); //remove those stupid parenthesis out.push_back(' '); } cout << out; return 0; }
以上是关于中缀符号到反波兰符号的主要内容,如果未能解决你的问题,请参考以下文章