Created
February 26, 2016 02:10
-
-
Save jrdalpra/b964190e669ff8df2c30 to your computer and use it in GitHub Desktop.
OO DoublyLinkedList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import lombok.AllArgsConstructor; | |
import lombok.ToString; | |
import lombok.val; | |
@ToString | |
public class DoublyLinkedList<T> { | |
private Node<T> first; | |
private Node<T> last; | |
public DoublyLinkedList() { | |
} | |
public void add(T item) { | |
if (this.first == null) { | |
this.first = this.last = new Node<>(null, item, null); | |
return; | |
} | |
val created = new Node<>(this.last, item, null); | |
this.last.next = created; | |
this.last = created; | |
} | |
public boolean isEmpty() { | |
return this.first == null; | |
} | |
@AllArgsConstructor | |
@ToString(of = "content") | |
private static class Node<T> { | |
private Node<T> previous; | |
private final T content; | |
private Node<T> next; | |
} | |
@AllArgsConstructor | |
public static class NormalIteration<T> implements Iterable<T> { | |
private final DoublyLinkedList<T> list; | |
@Override | |
public Iterator<T> iterator() { | |
return new DoublyLinkedListIterator<>(this.list, false); | |
} | |
} | |
@AllArgsConstructor | |
public static class ReversedIteration<T> implements Iterable<T> { | |
private final DoublyLinkedList<T> list; | |
@Override | |
public Iterator<T> iterator() { | |
return new DoublyLinkedListIterator<>(this.list, true); | |
} | |
} | |
private static class DoublyLinkedListIterator<T> implements Iterator<T> { | |
DoublyLinkedList<T> list; | |
Node<T> last; | |
boolean reversed; | |
public DoublyLinkedListIterator(DoublyLinkedList<T> list, boolean reversed) { | |
super(); | |
this.list = list; | |
this.reversed = reversed; | |
this.last = this.reversed ? this.list.last : this.list.first; | |
} | |
@Override | |
public boolean hasNext() { | |
return !this.list.isEmpty() && this.last != null; | |
} | |
@Override | |
public T next() { | |
val next = this.last.content; | |
this.last = reversed ? this.last.previous : this.last.next; | |
return next; | |
} | |
} | |
public static void main(String[] args) { | |
val list = new DoublyLinkedList<Integer>(); | |
list.add(1); | |
list.add(2); | |
list.add(3); | |
for (val item : new NormalIteration<>(list)) | |
System.out.println(item); | |
System.out.println(); | |
for (val item : new ReversedIteration<>(list)) | |
System.out.println(item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment