-
Notifications
You must be signed in to change notification settings - Fork 6.4k
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
37 lines (31 loc) · 873 Bytes
/
Copy pathDoublyLinkedList.java
File metadata and controls
37 lines (31 loc) · 873 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
package lrucache;
class DoublyLinkedList<K, V> {
private final Node<K, V> head;
private final Node<K, V> tail;
public DoublyLinkedList() {
head = new Node<>(null, null); // Dummy head
tail = new Node<>(null, null); // Dummy tail
head.next = tail;
tail.prev = head;
}
public void addFirst(Node<K, V> node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
public void remove(Node<K, V> node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
public void moveToFront(Node<K, V> node) {
remove(node);
addFirst(node);
}
public Node<K, V> removeLast() {
if (tail.prev == head) return null;
Node<K, V> last = tail.prev;
remove(last);
return last;
}
}