Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<string>
- #include<algorithm>
- #include<cctype>
- using namespace std;
- char stack[100000];
- int top=-1;
- void push(char ch) {
- top++;
- stack[top]=ch;
- }
- void pop () {
- top--;
- }
- int priority(char ch) {
- if(ch == '^') {return 3;}
- else if(ch == '*' || ch == '/' || ch == '%') {return 2;}
- else if(ch == '+' || ch == '-') {return 1;}
- else {return -1;}
- }
- int main () {
- string s;
- cin >> s;
- reverse(s.begin(),s.end());
- for(int i=0;i<s.length();i++) {
- if(s[i]=='(') {
- s[i]=')';
- }
- else if(s[i]==')') {
- s[i]='(';
- }
- }
- string s1;
- for(int i=0;i<s.length();i++) {
- if(isalnum(s[i])) {
- s1.push_back(s[i]);
- }
- else if(s[i]=='(') {
- push(s[i]);
- }
- else if(s[i]==')') {
- while(stack[top]!='(') {
- s1.push_back(stack[top]);
- pop();
- }
- top--;
- }
- else {
- while(priority(s[i]) <= priority(stack[top])) {
- s1.push_back(stack[top]); pop();
- }
- push(s[i]);
- }
- }
- for(int i=top;i>=0;i--) {
- s1.push_back(stack[i]);
- }
- reverse(s1.begin(),s1.end());
- cout << s1 << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment