-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixToPostfix.h
More file actions
87 lines (72 loc) · 2.17 KB
/
infixToPostfix.h
File metadata and controls
87 lines (72 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
#include <queue>
using namespace std;
string infixToPostfix(string equation);
int prec(char c);
//covert the infix equation to postfix
string infixToPostfix(string equation) {
//declare a stack to hold character
stack<char> st;
//declare a string variable for the result
string postfixEquation;
for(int i = 0; i < equation.length(); i++) {
//read each character form string equation
char c = equation[i];
// If the scanned character is an digit,
// check if next character is digit until get operator
// add it to output string.
while(isdigit(c) || c == '.') {
postfixEquation += c;
i += 1;
c = equation[i];
}
// If the scanned character is an
// ‘(‘, push it to the stack.
if(c == '(')
st.push(c);
// If the scanned character is an ‘)’,
// pop and to output string from the stack
// until an ‘(‘ is encountered.
else if(c == ')') {
while(st.top() != '(')
{
postfixEquation += st.top();
st.pop();
}
st.pop();
}
//If an operator is scanned
else {
//determine if stack is empty and compare the precdence
while(!st.empty() && prec(equation[i]) <= prec(st.top())) {
//output the most higher procedence
postfixEquation += st.top();
//delect it from stack
st.pop();
}
//add current character to stack
st.push(c);
}
//seprate operands
postfixEquation += " ";
}
// Pop all the remaining elements from the stack
while(!st.empty()) {
postfixEquation += st.top();
st.pop();
}
return postfixEquation;
}
//Function to return precedence of operators
int prec(char c) {
if(c == '^')
return 3;
else if(c == '/' || c == '*')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}