Skip to content

Commit 49c91eb

Browse files
committed
Polish example linked-list exercise
Apply generics to the internals of Element to remove needless casting. Tighten Element scoping and move into Deque for succintness (sp). Add the execise into the grade test suite.
1 parent 3460389 commit 49c91eb

3 files changed

Lines changed: 29 additions & 68 deletions

File tree

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,57 @@
11
public final class Deque<T> {
2-
private Element head;
2+
private Element<T> head;
33

44
public void push(T value) {
55
if (head == null) {
6-
head = new Element(value, null, null);
7-
head.setNext(head);
8-
head.setPrev(head);
6+
head = new Element<>(value, null, null);
7+
head.next = head;
8+
head.prev = head;
99
return;
1010
}
1111

12-
Element oldTail = head.getPrev();
13-
Element tail = new Element(value, oldTail, head);
14-
oldTail.setNext(tail);
15-
head.setPrev(tail);
12+
Element<T> oldTail = head.prev;
13+
Element<T> tail = new Element<>(value, oldTail, head);
14+
oldTail.next = tail;
15+
head.prev = tail;
1616
}
1717

1818
public T pop() {
19-
head = head.getPrev();
19+
head = head.prev;
2020
return shift();
2121
}
2222

2323
public void unshift(T value) {
2424
push(value);
25-
head = head.getPrev();
25+
head = head.prev;
2626
}
2727

2828
public T shift() {
29-
Object value = head.getValue();
29+
T value = head.value;
3030

31-
Element newHead = head.getNext();
32-
Element newTail = head.getPrev();
31+
Element<T> newHead = head.next;
32+
Element<T> newTail = head.prev;
3333

3434
if (newHead == head) {
3535
head = null;
3636
}
3737
else {
38-
newHead.setPrev(newTail);
39-
newTail.setNext(newHead);
38+
newHead.prev = newTail;
39+
newTail.next = newHead;
4040
head = newHead;
4141
}
4242

43-
return (T) value;
43+
return value;
44+
}
45+
46+
private static final class Element<T> {
47+
private final T value;
48+
private Element<T> prev;
49+
private Element<T> next;
50+
51+
public Element(T value, Element<T> prev, Element<T> next) {
52+
this.value = value;
53+
this.prev = prev;
54+
this.next = next;
55+
}
4456
}
4557
}

‎linked-list/src/example/java/Element.java‎

Lines changed: 0 additions & 52 deletions
This file was deleted.

‎settings.gradle‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ include 'grade-school'
1111
include 'hamming'
1212
include 'hexadecimal'
1313
include 'hello-world'
14+
include 'linked-list'
1415
include 'luhn'
1516
include 'meetup'
1617
include 'nucleotide-count'

0 commit comments

Comments
 (0)