File tree 1 file changed +115
-0
lines changed
src/_DataStructures_/Stack/2-stacks-using1-array
1 file changed +115
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TwoStacks {
2
+ constructor ( ) {
3
+ this . data = [ ] ;
4
+ this . top1 = null ;
5
+ this . top2 = null ;
6
+ this . stack1Count = 0 ;
7
+ this . stack2Count = 0 ;
8
+ }
9
+
10
+ push1 ( value ) {
11
+ if ( ! this . data . length ) {
12
+ this . data . push ( value ) ;
13
+ this . top1 = value ;
14
+ this . stack1Count += 1 ;
15
+ } else {
16
+ const arr = [ ] ;
17
+ for ( let i = 0 ; i < this . stack1Count ; i += 1 ) {
18
+ arr . push ( this . data [ i ] ) ;
19
+ }
20
+ arr . push ( value ) ;
21
+ for ( let i = this . stack1Count ; i < this . data . length ; i += 1 ) {
22
+ arr . push ( this . data [ i ] ) ;
23
+ }
24
+ this . data = arr ;
25
+ this . top1 = value ;
26
+ this . stack1Count += 1 ;
27
+ }
28
+ }
29
+
30
+ push2 ( value ) {
31
+ if ( ! this . data . length ) {
32
+ this . data . push ( value ) ;
33
+ this . top2 = value ;
34
+ this . stack2Count += 1 ;
35
+ } else {
36
+ const arr = [ ] ;
37
+ for ( let i = 0 ; i < this . stack1Count ; i += 1 ) {
38
+ arr . push ( this . data [ i ] ) ;
39
+ }
40
+ arr . push ( value ) ;
41
+
42
+ for ( let i = this . stack1Count ; i < this . data . length ; i += 1 ) {
43
+ arr . push ( this . data [ i ] ) ;
44
+ }
45
+ this . data = arr ;
46
+ this . top2 = value ;
47
+ this . stack2Count += 1 ;
48
+ }
49
+ }
50
+
51
+ pop1 ( ) {
52
+ if ( ! this . top1 ) {
53
+ return null ;
54
+ }
55
+
56
+ const indexOfTop1 = this . data . indexOf ( this . top1 ) ;
57
+ const arr = [ ] ;
58
+
59
+ delete this . data [ indexOfTop1 ] ;
60
+
61
+ this . data . forEach ( el => arr . push ( el ) ) ;
62
+
63
+ const oldTop = this . top1 ;
64
+ this . top1 = this . data [ indexOfTop1 - 1 ] ;
65
+ this . data = arr ;
66
+ return oldTop ;
67
+ }
68
+
69
+ pop2 ( ) {
70
+ return this . data . pop ( ) ;
71
+ }
72
+ }
73
+
74
+ module . exports = TwoStacks ;
75
+
76
+ /** Test cases */
77
+
78
+ /*
79
+
80
+ const s = new TwoStacks();
81
+
82
+ console.log(s.data);
83
+
84
+ s.push1(5);
85
+ s.push1(4);
86
+ console.log(s.data);
87
+
88
+
89
+ s.push2(2)
90
+ s.push2(1);
91
+ console.log(s.data);
92
+
93
+ s.push1(14);
94
+ console.log(s.data);
95
+ console.log(s.top1);
96
+
97
+ console.log(s.pop1())
98
+ console.log(s.data);
99
+
100
+ console.log(s.pop1())
101
+ console.log(s.data);
102
+
103
+ console.log(s.pop2())
104
+ console.log(s.data);
105
+
106
+ console.log(s.pop2())
107
+ console.log(s.data);
108
+
109
+ console.log(s.pop2())
110
+ console.log(s.data);
111
+
112
+ console.log(s.pop1())
113
+ console.log(s.data);
114
+
115
+ */
You can’t perform that action at this time.
0 commit comments