Skip to content

Commit a268bba

Browse files
committed
Implement a O(1) stack
1 parent 027b8a0 commit a268bba

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

src/main/lists/Stack.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* An implementation of a stack based on a linked list.
3+
*
4+
* <p>
5+
* The head of the linked list is the top of the stack. All operations are O(1)
6+
* in time and space complexity. The length (or size) of the stack is not stored
7+
* and thus cannot be retrieved in constant time.
8+
*
9+
* <p>
10+
* This implementation also does not contain any if statement thanks to two
11+
* techniques: not storing the length (as described above) and having a tail
12+
* whose <code>next</code> pointer points to itself.
13+
*
14+
* <p>
15+
* Operations with their time complexities are:
16+
* <ul>
17+
* <li><code>push</code>: O(1)</li>
18+
* <li><code>pop</code>: O(1)</li>
19+
* <li><code>peek</code>: O(1)</li>
20+
* </ul>
21+
*/
22+
public class Stack<T> {
23+
private LinkedListNode<T> head;
24+
25+
public Stack() {
26+
LinkedListNode<T> tail = new LinkedListNode<T>(null, null);
27+
tail.next = tail;
28+
29+
this.head = new LinkedListNode<T>(null, tail);
30+
}
31+
32+
public Stack(T[] data) {
33+
LinkedListNode<T> tail = new LinkedListNode<T>(null, null);
34+
tail.next = tail;
35+
36+
this.head = new LinkedListNode<T>(null, new LinkedListNode<T>(null, null));
37+
38+
for (T d: data)
39+
this.push(d);
40+
}
41+
42+
public boolean isEmpty() {
43+
return this.head.next == this.head.next.next;
44+
}
45+
46+
public Stack<T> push(T data) {
47+
this.head.next = new LinkedListNode<T>(data, this.head.next);
48+
return this;
49+
}
50+
51+
public Stack<T> pop() {
52+
this.head.next = this.head.next.next;
53+
return this;
54+
}
55+
56+
public T peek() {
57+
return this.head.next.data;
58+
}
59+
}

0 commit comments

Comments
 (0)