-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.java
69 lines (58 loc) · 1.5 KB
/
LinkedList.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package net.reservoircode.structures;
public class LinkedList<T> {
private Node<T> first, last;
private Integer size = 0;
public void add(T value) {
if (size == 0) {
first = new Node<>(value, null, null);
} else {
Node<T> current = new Node<>(value, first, null);
last = current;
}
size++;
}
public T removeFirst() {
if (size == 0) {
throw new IllegalStateException("No element available");
}
if (first.next == null) {
T value = first.value;
first = null;
size--;
return value;
}
Node<T> current = first;
while (current.next != null) {
current = current.next;
}
final T value = current.value;
current = null;
size--;
return value;
}
public T removeLast() {
if (size == 0) {
throw new IllegalStateException("No element available");
}
T value = first.value;
first = first.next;
size--;
return value;
}
public T getLast() {
return first.value;
}
public Integer size() {
return size;
}
private static class Node<T> {
private final T value;
private Node<T> prev;
private Node<T> next;
public Node(T value, Node<T> prev, Node<T> next) {
this.value = value;
this.prev = prev;
this.next = next;
}
}
}