-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathreversePolishNotation.js
82 lines (69 loc) · 2.17 KB
/
reversePolishNotation.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
class MyStack {
constructor() {
this.array = []; // Array is used to implement stack
}
// List of main functions of stack data structure
push(value) {
// push an element into the array
this.array.push(value);
}
pop() {
// Underflow if stack is empty
if (this.isEmpty()) {
return "Underflow";
}
return this.array.pop(); // return top most element from the stack and removes the same element
}
peek() {
return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
}
// List of helper functions
isEmpty() {
return this.array.length === 0; // return true if stack is empty
}
printStack() {
let data = "";
for (let el of this.array)
data += el + " ";
return data;
}
}
function reversePolishNotation(tokens){
let myStack = new MyStack();
for (const token of tokens) {
switch (token) {
case '+': {
let secondPrev = myStack.pop();
let firstPrev = myStack.pop();
myStack.push(firstPrev+secondPrev);
break;
}
case '-': {
let secondPrev = myStack.pop();
let firstPrev = myStack.pop();
myStack.push(firstPrev-secondPrev);
break;
}
case '*': {
let secondPrev = myStack.pop();
let firstPrev = myStack.pop();
myStack.push(firstPrev*secondPrev);
break;
}
case '/': {
let secondPrev = myStack.pop();
let firstPrev = myStack.pop();
myStack.push(Number.parseInt(firstPrev/secondPrev));
break;
}
default:
myStack.push(Number.parseInt(token));
break;
}
}
return myStack.pop();
}
let tokens1 = ["1","3","+","4","*"];
let tokens2 = ["5","4","3","2","+","-10","*","/","*","10","+","4","+"];
console.log(reversePolishNotation(tokens1));
console.log(reversePolishNotation(tokens2));