forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinfixtoprefix.js
143 lines (122 loc) · 2.7 KB
/
infixtoprefix.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/*
This code converts infix expression to prefix expression in JavaScript.
Infix expression:- The expression of the form a op b.
When an operator is in-between every pair of operands.
Prefix expression:- An expression is called the prefix expression
if the operator appears in the expression before the operands.
Simply of the form (operand1 operand2 operator).
*/
var stackarr=[];
var topp=-1;
//function for push in stack
function push(e)
{
topp++;
stackarr[topp]=e;
}
// function for popping out from stack
function pop()
{
if(topp==-1)
return 0;
else
{
var popped_ele=stackarr[topp];
topp--;
return popped_ele;
}
}
//function to check is operator or not
function operator(op)
{
return ((op=='+' || op=='-' || op=='^' || op=='*' || op=='/' || op=='(' || op==')')? true:false);
}
// function for checking precedency
function precedency(pre)
{
if(pre=='@' || pre=='(' || pre==')')
{
return 1;
}
else if(pre=='+' || pre=='-')
{
return 2;
}
else if (pre=='/' || pre=='*')
{
return 3;
}
else if(pre=='^')
{
return 4;
}
else
return 0;
}
// function for infix to prefix conversion
function InfixtoPrefix(infixval)
{
var prefix=[];
var temp=0;
push('@');
for(var i=infixval.length-1;i>=0;i--)
{
var el=infixval[i];
if(operator(el))
{
if (el =='(') {
while (stackarr[topp] != ")") {
prefix[temp++] = pop();
}
pop();
}
else if(el==')')
{
push(el);
}
// function for comparing precedency
else if(precedency(el)>precedency(stackarr[topp]))
{
push(el);
}
else
{
while(precedency(el)<=precedency(stackarr[topp])&&topp>-1)
{
prefix[temp++]=pop();
}
push(el);
}
}
else{
prefix[temp++]=el;
}
}
while(stackarr[topp]!='@')
{
prefix[temp++]=pop();
}
var st="";
for(var j=prefix.length-1;j>=0;j--)
{
st+=prefix[j];
}
console.log("Prefix Expression:- "+st);
}
InfixtoPrefix("((a+b)*c)");
/*
Input:
Enter a valid Prefix Expression:- ((a+b)*c)
OutPut:
Prefix Expression:- *+abc
Input:
Enter a valid Prefix Expression:- A+B*C/(E-F)
Output:
Prefix Expression:- +A*B/C-EF
Input:
Enter a valid Prefix Expression:- a+b*(c^d-e)^(f+g*h)-i
Output:
Prefix Expression:- +a-*b^-^cde+f*ghi
Time Complexity:O(N)
Space Complexity: O(N)
*/