File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * An implementation of stack using static array.
3+ *
4+ * <p>
5+ * Operations with their time complexities are:
6+ * <ul>
7+ * <li><code>push</code>: O(1)</li>
8+ * <li><code>pop</code>: O(1)</li>
9+ * <li><code>peek</code>: O(1)</li>
10+ * </ul>
11+ *
12+ */
13+ public class ArrayStack <T > {
14+ private Object [] array ;
15+ private int length ;
16+
17+ public ArrayStack (int capacity ) {
18+ this .array = new Object [capacity ];
19+ this .length = 0 ;
20+ }
21+
22+ public int getLength () {
23+ return this .length ;
24+ }
25+
26+ public int getCapacity () {
27+ return this .array .length ;
28+ }
29+
30+ public ArrayStack <T > push (T data ) {
31+ if (this .length == this .array .length )
32+ return this ;
33+
34+ this .array [this .length ++] = data ;
35+ return this ;
36+ }
37+
38+ public ArrayStack <T > pop () {
39+ if (this .length == 0 )
40+ return this ;
41+
42+ this .array [--this .length ] = null ;
43+ return this ;
44+ }
45+
46+ @ SuppressWarnings ("unchecked" )
47+ public T peek () {
48+ return (this .length == 0 ) ? null : (T ) this .array [this .length - 1 ];
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments