Repository navigation
Expand file tree
/
Copy pathPostfix.html
More file actions
124 lines (105 loc) · 3.59 KB
/
Copy pathPostfix.html
File metadata and controls
124 lines (105 loc) · 3.59 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Evaluation of postfix Expression</title>
</head>
<body>
<script>
// Stack class
class Stack {
// Array is used to implement stack
constructor () {
this.items = [];
}
// Functions to be implemented
// push(item)
// pop()
// peek()
// isEmpty()
// printStack()
// push function
push(element)
{
// push element into the items
this.items.push(element);
}
// pop function
pop()
{
// return top most element in the stack
// and removes it from the stack
// Underflow if stack is empty
if(this.items.length == 0)
return "Underflow";
return this.items.pop();
}
// peek function
peek()
{
// return the top most element from the stack
// but does'nt delete it.
return this.items[this.items.length-1];
}
// isEmpty function
isEmpty()
{
// return true if stack is empty
return this.items.length == 0;
}
// printStack function
printStack()
{
var str = "";
for(var i = 0; i < this.items.length; i++)
str += this.items[i] +" ";
return str;
}
size(){
return this.items.length;
}
clear(){
this.items = [];
}
toString(){
return this.items.toString();
}
}
// Performs Postfix Evaluation on a given exp
function postFixEvaluation(exp){
var stack = new Stack();
for(var i = 0; i < exp.length ; i++)
{
var c = exp[i];
if(!isNaN(c))
stack.push(c - '0');
else{
var val1 = stack.pop();
var val2 = stack.pop();
if(val1 == "Underflow" || val2 == "Underflow")
return "Can't perform postfix evaluation";
switch(c)
{
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
// calling the above method
console.log(postFixEvaluation("235*+8-")); // returns 9
console.log(postFixEvaluation("23*+"));
// returns postfix evaluation can't be performed
</script>
</body>
</html>