File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -79,4 +79,43 @@ public void increment(int k, int val) {
7979 }
8080 }
8181 }
82+
83+ /**
84+ * Implementation of Stack using Array
85+ */
86+ public static class Solution2 {
87+ public static class CustomStack {
88+ private int top ;
89+ private int maxSize ;
90+ private int stack [];
91+ public CustomStack (int maxSize ) {
92+ this .maxSize = maxSize ;
93+ this .stack = new int [maxSize ];
94+ }
95+
96+ public void push (int x ) {
97+ if (top == maxSize ) return ;
98+ stack [top ] = x ;
99+ top ++;
100+ }
101+
102+ public int pop () {
103+ if (top == 0 )
104+ return -1 ;
105+ int popValue = stack [top -1 ];
106+ stack [top -1 ] = 0 ;
107+ top --;
108+ return popValue ;
109+ }
110+
111+ public void increment (int k , int val ) {
112+ if (top == 0 || k == 0 ) return ;
113+ for (int i = 0 ; i <k ; i ++){
114+ if (i == top )
115+ break ;
116+ stack [i ] += val ;
117+ }
118+ }
119+ }
120+ }
82121}
Original file line number Diff line number Diff line change 77
88public class _1381Test {
99 private static _1381 .Solution1 .CustomStack customStack ;
10+ private static _1381 .Solution2 .CustomStack customStack2 ;
1011
1112 @ Test
1213 public void test1 () {
@@ -24,5 +25,20 @@ public void test1() {
2425 assertEquals (201 , customStack .pop ());
2526 assertEquals (-1 , customStack .pop ());
2627 }
28+ @ Test
29+ public void test2 () {
30+ customStack2 = new _1381 .Solution2 .CustomStack (3 );
31+ customStack2 .push (-1 );
32+ customStack2 .push (20 );
33+ assertEquals (20 , customStack2 .pop ());
34+ customStack2 .push (30 );
35+ customStack2 .push (40 );
36+ customStack2 .push (50 );
37+ customStack2 .increment (5 , 100 );
38+ assertEquals (140 , customStack2 .pop ());
39+ assertEquals (130 , customStack2 .pop ());
40+ assertEquals (99 , customStack2 .pop ());
41+
42+ }
2743
2844}
You can’t perform that action at this time.
0 commit comments