This repository has been archived by the owner on Nov 5, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPostfix.cpp
99 lines (81 loc) · 1.63 KB
/
InfixToPostfix.cpp
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
88
89
90
91
92
93
94
95
96
97
98
99
// Infix to Postfix
#include<iostream>
#include<string>
using namespace std;
int top = -1;
int stack[10];
bool stackEmpty(){
if(top==-1)
return true;
else
return false;
}
bool stackFull(){
if(top>=9)
return true;
else
return false;
}
void push(char ele){
if(stackFull())
cout << "Stack Full. Cannot insert!" << endl;
else
stack[++top] = ele;
}
void pop(char &dataOut){
if(stackEmpty())
cout << "Stack empty. Cannot pop!" << endl;
else{
dataOut = stack[top--];
}
}
int priority(char op){
if(op == '+' || op == '-')
return 1;
else if(op == '*' || op == '/')
return 2;
else
return 0;
}
string inToPostFix(string formula){
char postFixExpr[50];
int count=0;
for(int i=0; i<formula.length(); i++){
if(formula[i] == '(')
push(formula[i]);
else if(formula[i] == ')'){
char dataOut;
pop(dataOut);
while(formula[i] != '('){
postFixExpr[count++] = formula[i];
pop(dataOut);
}
}
else if(formula[i] == '+' || formula[i] == '-' || formula[i] == '*' || formula[i] == '/' || formula[i] == '%'){
char tokenOut;
while(!stackEmpty() && priority(formula[i]) <= priority(stack[top])){
pop(tokenOut);
postFixExpr[count++] = tokenOut;
}
push(formula[i]);
}
else{
postFixExpr[count++] = formula[i];
}
}
while(!stackEmpty()){
char dataOut;
pop(dataOut);
postFixExpr[count++] = dataOut;
}
string postFix = "";
for(int i=0; i<count; i++){
postFix+=postFixExpr[i];
}
return postFix;
}
int main(){
string inputExpr;
cout << "Enter infix expression: "; cin >> inputExpr;
cout << "The corresponding postfix expression is: "<< inToPostFix(inputExpr) << endl;
}