-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathindex.js
122 lines (96 loc) · 2.18 KB
/
index.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
/**
* So what special in this implementation?
* This deals with Dynamic array without a size hence the implemetation uses
* lot of space and I can sense that it can be further improved hence feel free
* to open PR
*/
class TwoStacks {
constructor() {
this.data = [];
this.top1 = null;
this.top2 = null;
this.stack1Count = 0;
this.stack2Count = 0;
}
push1(value) {
if (!this.data.length) {
this.data.push(value);
this.top1 = value;
this.stack1Count += 1;
} else {
const arr = [];
for (let i = 0; i < this.stack1Count; i += 1) {
arr.push(this.data[i]);
}
arr.push(value);
for (let i = this.stack1Count; i < this.data.length; i += 1) {
arr.push(this.data[i]);
}
this.data = arr;
this.top1 = value;
this.stack1Count += 1;
}
}
push2(value) {
if (!this.data.length) {
this.data.push(value);
this.top2 = value;
this.stack2Count += 1;
} else {
const arr = [];
for (let i = 0; i < this.stack1Count; i += 1) {
arr.push(this.data[i]);
}
arr.push(value);
for (let i = this.stack1Count; i < this.data.length; i += 1) {
arr.push(this.data[i]);
}
this.data = arr;
this.top2 = value;
this.stack2Count += 1;
}
}
pop1() {
if (!this.top1) {
return null;
}
const indexOfTop1 = this.data.indexOf(this.top1);
const arr = [];
delete this.data[indexOfTop1];
this.data.forEach(el => arr.push(el));
const oldTop = this.top1;
this.top1 = this.data[indexOfTop1 - 1];
this.data = arr;
return oldTop;
}
pop2() {
return this.data.pop();
}
}
module.exports = TwoStacks;
/** Test cases */
/*
const s = new TwoStacks();
console.log(s.data);
s.push1(5);
s.push1(4);
console.log(s.data);
s.push2(2)
s.push2(1);
console.log(s.data);
s.push1(14);
console.log(s.data);
console.log(s.top1);
console.log(s.pop1())
console.log(s.data);
console.log(s.pop1())
console.log(s.data);
console.log(s.pop2())
console.log(s.data);
console.log(s.pop2())
console.log(s.data);
console.log(s.pop2())
console.log(s.data);
console.log(s.pop1())
console.log(s.data);
*/