-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.java
More file actions
50 lines (42 loc) · 992 Bytes
/
Stack.java
File metadata and controls
50 lines (42 loc) · 992 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Implementations;
public class Stack<T> {
private StackItem<T> root;
private int size = 0;
public void push(T value){
root = new StackItem<>(value, root);
size++;
}
public T pop(){
T out = root.value;
root = root.nextItem;
size--;
return out;
}
public T peek(){
return root.value;
}
public int getSize(){
return size;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[ ");
StackItem item = root;
while (item != null){
sb.append(item.value.toString());
if(item.nextItem != null)
sb.append(", ");
item = item.nextItem;
}
sb.append(" ]");
return sb.toString();
}
}
class StackItem<T>{
T value;
StackItem nextItem;
StackItem(T value, StackItem nextItem){
this.value = value;
this.nextItem = nextItem;
}
}