forked from Minor-lazer/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixToPrefix.cpp
More file actions
104 lines (91 loc) · 1.93 KB
/
infixToPrefix.cpp
File metadata and controls
104 lines (91 loc) · 1.93 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<iostream>
#include<string.h>
using namespace std;
struct Stack{
int top;
int size;
int *array;
};
struct Stack *createStack(int n){
struct Stack *stack = new Stack();
stack->top = -1;
stack->size = n;
stack->array = new int[n];
return stack;
}
int isEmpty(struct Stack *stack){
return stack->top == -1;
}
char peek(struct Stack *stack){
return stack->array[stack->top];
}
char pop(struct Stack *stack){
if(!isEmpty(stack))
return stack->array[stack->top--];
return '$';
}
void push(struct Stack* stack, char ip){
stack->array[++stack->top] = ip;
}
int isOperand(char ch){
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int Precedence(char ch){
if(ch == '+' || ch == '-')
return 1;
else if(ch == '*' || ch == '/')
return 2;
else if(ch == '^')
return 3;
else
return -1;
}
int infixToPrefix(string input){
int i;
int k = -1;
string output, output2;
Stack *stack = createStack(input.length());
for(i=0; i < input.length(); i++){
if(isOperand(input[i]))
output += input[i];
else if(input[i] == '(')
push(stack, input[i]);
else if(input[i] == ')'){
while(!isEmpty(stack) && peek(stack) != '(')
output += pop(stack);
if(peek(stack) == '(')
pop(stack);
}
else{
while(!isEmpty(stack) && Precedence(input[i]) <= Precedence(peek(stack)))
output += pop(stack);
push(stack, input[i]);
}
}
while(!isEmpty(stack))
output += pop(stack);
string::reverse_iterator it;
for(it = output.rbegin(); it != output.rend(); it++){
if(*it == '(')
*it = ')';
else if(*it == ')')
*it = '(';
output2 += *it;
}
cout << "Prefix: ";
cout << output2 << endl;
}
int main(){
string input, exp;
string::reverse_iterator it;
cout << "Enter infix expression: ";
cin >> input;
for(it = input.rbegin(); it != input.rend(); it++){
if(*it == '(')
*it = ')';
else if(*it == ')')
*it = '(';
exp += *it;
}
infixToPrefix(exp);
}