-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathToPostfix.js
92 lines (80 loc) · 1.74 KB
/
ToPostfix.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
/*
* Author: Harinath-B (https://github.com/Harinath-B)
* Infix and POstfix notation explanation can be found in the following links:
* Wikipedia: https://en.wikipedia.org/wiki/Infix_notation / https://en.wikipedia.org/wiki/Reverse_Polish_notation
*/
class Stack {
constructor () {
this.stack = []
this.top = -1
}
// Adds a value to the end of the Stack
push (newValue) {
this.stack.push(newValue)
this.top++
}
// Returns and removes the last element of the Stack
pop () {
if (this.top !== -1) {
this.top--
return this.stack.pop()
}
throw new Error('Stack Underflow')
}
// Returns the number of elements in the Stack
length () {
return this.top
}
// Returns true if stack is empty, false otherwise
isEmpty () {
return this.top === -1
}
// Returns the last element without removing it
last () {
if (this.top !== -1) {
return this.stack[this.stack.length]
}
return null
}
}
const isAlNum = (c) => {
return c.match(/^[a-z0-9]+$/i) !== null
}
const priority = (op) => {
if (op === '+' || op === '-') {
return 1
}
else if (op === '*' || op === '/'){
return 2
}
return 0
}
function ToPostfix(infix) {
let postfix = ''
let opStack = new Stack()
for (const c of infix) {
if (isAlNum(c)) {
postfix += c
}
else if (c === '('){
opStack.push(c)
}
else if (c === ')') {
let x = ''
while ((x = opStack.pop()) != '('){
postfix += x
}
}
else {
while (priority(opStack.stack) > priority(c)) {
postfix += opStack.pop()
}
opStack.push(c)
}
}
while (opStack.top !== -1) {
postfix += opStack.pop()
}
return postfix
}
export { ToPostfix }