Skip to content

Commit 7753977

Browse files
committed
fix: correct implementation of all the methods, keeping rules inact
1 parent 9e858fc commit 7753977

File tree

1 file changed

+40
-11
lines changed
  • src/_DataStructures_/Stack/2-stacks-using1-array

1 file changed

+40
-11
lines changed

src/_DataStructures_/Stack/2-stacks-using1-array/index.js

+40-11
Original file line numberDiff line numberDiff line change
@@ -8,39 +8,60 @@
88
class TwoStacks {
99
constructor(capacity) {
1010
this.data = [];
11-
this.capacity = capacity;
1211
this.top1 = -1;
1312
this.top2 = capacity;
13+
14+
this.capacity = capacity;
15+
this.total = 0;
1416
}
1517

1618
push1(value) {
17-
if (this.top1 === -1 || this.top1 < this.top2 - 1) {
19+
if (this.total >= this.capacity + 1) {
20+
throw new Error('Overflow');
21+
}
22+
if (this.top1 < this.top2 - 1) {
1823
this.top1 += 1;
1924
this.data[this.top1] = value;
20-
return;
25+
this.total += 1;
2126
}
22-
throw new Error('Overflow');
2327
}
2428

2529
push2(value) {
26-
if (this.top2 <= this.capacity && this.top2 > this.top1) {
27-
this.data[this.top2] = value;
30+
if (this.total >= this.capacity + 1) {
31+
throw new Error('Overflow');
32+
}
33+
if (this.top1 < this.top2 - 1) {
2834
this.top2 -= 1;
29-
return;
35+
this.data[this.top2] = value;
36+
this.total += 1;
3037
}
31-
throw new Error('Overflow');
3238
}
3339

34-
pop1() {}
40+
pop1() {
41+
if (this.top1 >= 0) {
42+
const item = this.data[this.top1];
43+
this.top1 -= 1;
44+
return item;
45+
}
46+
return -1;
47+
}
3548

36-
pop2() {}
49+
pop2() {
50+
if (this.top2 < this.capacity) {
51+
const item = this.data[this.top2];
52+
this.top2 += 1;
53+
return item;
54+
}
55+
return -1;
56+
}
3757
}
3858

3959
module.exports = TwoStacks;
4060

4161
/** Test cases */
4262

43-
const s = new TwoStacks(3);
63+
/*
64+
const s = new TwoStacks(4);
4465
4566
s.push1('a');
4667
console.log(s.data);
@@ -56,3 +77,11 @@ console.log(s.data);
5677
5778
s.push2('b3');
5879
console.log(s.data);
80+
81+
console.log(s.pop2());
82+
console.log(s.data);
83+
84+
console.log(s.pop1());
85+
console.log(s.data);
86+
87+
*/

0 commit comments

Comments
 (0)