1
1
package com .bobocode .stack ;
2
2
3
3
import com .bobocode .stack .exception .EmptyStackException ;
4
- import com .bobocode .util .ExerciseNotCompletedException ;
4
+
5
+ import java .util .Objects ;
6
+ import java .util .stream .Stream ;
5
7
6
8
/**
7
9
* {@link LinkedStack} represents a last-in-first-out (LIFO) stack of objects that is based on singly linked generic nodes.
10
12
* @param <T> generic type parameter
11
13
*/
12
14
public class LinkedStack <T > implements Stack <T > {
15
+ private static class Node <T > {
16
+ T element ;
17
+ Node <T > next ;
18
+
19
+ public static <T > Node <T > valueOf (T element ) {
20
+ return new Node <>(element );
21
+ }
22
+
23
+ private Node (T element ) {
24
+ this .element = element ;
25
+ }
26
+ }
27
+
28
+ private Node <T > head ;
29
+ private int size = 0 ;
13
30
14
31
/**
15
32
* This method creates a stack of provided elements
@@ -19,7 +36,9 @@ public class LinkedStack<T> implements Stack<T> {
19
36
* @return a new stack of elements that were passed as method parameters
20
37
*/
21
38
public static <T > LinkedStack <T > of (T ... elements ) {
22
- throw new ExerciseNotCompletedException (); // todo: implement this method
39
+ LinkedStack <T > linkedStack = new LinkedStack <>();
40
+ Stream .of (elements ).forEach (linkedStack ::push );
41
+ return linkedStack ;
23
42
}
24
43
25
44
/**
@@ -30,7 +49,13 @@ public static <T> LinkedStack<T> of(T... elements) {
30
49
*/
31
50
@ Override
32
51
public void push (T element ) {
33
- throw new ExerciseNotCompletedException (); // todo: implement this method
52
+ Objects .requireNonNull (element );
53
+ Node <T > newNode = Node .valueOf (element );
54
+ if (head != null ) {
55
+ newNode .next = head ;
56
+ }
57
+ head = newNode ;
58
+ size ++;
34
59
}
35
60
36
61
/**
@@ -42,7 +67,18 @@ public void push(T element) {
42
67
*/
43
68
@ Override
44
69
public T pop () {
45
- throw new ExerciseNotCompletedException (); // todo: implement this method
70
+ if (head != null ) {
71
+ size --;
72
+ return retrieveHead ();
73
+ } else {
74
+ throw new EmptyStackException ();
75
+ }
76
+ }
77
+
78
+ private T retrieveHead () {
79
+ T element = head .element ;
80
+ this .head = head .next ;
81
+ return element ;
46
82
}
47
83
48
84
/**
@@ -52,7 +88,7 @@ public T pop() {
52
88
*/
53
89
@ Override
54
90
public int size () {
55
- throw new ExerciseNotCompletedException (); // todo: implement this method
91
+ return size ;
56
92
}
57
93
58
94
/**
@@ -62,6 +98,6 @@ public int size() {
62
98
*/
63
99
@ Override
64
100
public boolean isEmpty () {
65
- throw new ExerciseNotCompletedException (); // todo: implement this method ;
101
+ return head == null ;
66
102
}
67
103
}
0 commit comments