Skip to content

Commit ab5f675

Browse files
committed
ArrayStack: Add stack implementation using array
1 parent 8861a66 commit ab5f675

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

src/main/lists/ArrayStack.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)