File tree 1 file changed +40
-11
lines changed
src/_DataStructures_/Stack/2-stacks-using1-array
1 file changed +40
-11
lines changed Original file line number Diff line number Diff line change 8
8
class TwoStacks {
9
9
constructor ( capacity ) {
10
10
this . data = [ ] ;
11
- this . capacity = capacity ;
12
11
this . top1 = - 1 ;
13
12
this . top2 = capacity ;
13
+
14
+ this . capacity = capacity ;
15
+ this . total = 0 ;
14
16
}
15
17
16
18
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 ) {
18
23
this . top1 += 1 ;
19
24
this . data [ this . top1 ] = value ;
20
- return ;
25
+ this . total += 1 ;
21
26
}
22
- throw new Error ( 'Overflow' ) ;
23
27
}
24
28
25
29
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 ) {
28
34
this . top2 -= 1 ;
29
- return ;
35
+ this . data [ this . top2 ] = value ;
36
+ this . total += 1 ;
30
37
}
31
- throw new Error ( 'Overflow' ) ;
32
38
}
33
39
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
+ }
35
48
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
+ }
37
57
}
38
58
39
59
module . exports = TwoStacks ;
40
60
41
61
/** Test cases */
42
62
43
- const s = new TwoStacks ( 3 ) ;
63
+ /*
64
+ const s = new TwoStacks(4);
44
65
45
66
s.push1('a');
46
67
console.log(s.data);
@@ -56,3 +77,11 @@ console.log(s.data);
56
77
57
78
s.push2('b3');
58
79
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
+ */
You can’t perform that action at this time.
0 commit comments