115 lines
2.3 KiB
Java
115 lines
2.3 KiB
Java
package net.abhinavsarkar.algorist;
|
|
|
|
import java.util.Objects;
|
|
import java.util.Optional;
|
|
import java.util.function.Function;
|
|
|
|
public class LinkedList<T>
|
|
{
|
|
private Node<T> head;
|
|
|
|
public LinkedList(Node<T> head)
|
|
{
|
|
Objects.nonNull(head);
|
|
this.head = head;
|
|
}
|
|
|
|
public static class Node<T>
|
|
{
|
|
|
|
private T value;
|
|
private Node<T> next;
|
|
public Node(T value, Node<T> next)
|
|
{
|
|
this.value = value;
|
|
this.next = next;
|
|
}
|
|
|
|
}
|
|
|
|
public T head() {
|
|
return head.value;
|
|
}
|
|
|
|
public LinkedList<T> tail() {
|
|
return head.next != null ? new LinkedList<>(head.next) : null;
|
|
}
|
|
|
|
public void prepend(Node<T> vNode)
|
|
{
|
|
vNode.next = head;
|
|
head = vNode;
|
|
}
|
|
|
|
public <U> Optional<U> forEach(Function<T, Optional<U>> f) {
|
|
LinkedList<T> l = this;
|
|
LinkedList<T> t;
|
|
|
|
do {
|
|
t = l.tail();
|
|
T h = l.head();
|
|
Optional<U> r = f.apply(h);
|
|
if (r.isPresent()) {
|
|
return r;
|
|
}
|
|
l = t;
|
|
} while (t != null);
|
|
return Optional.empty();
|
|
}
|
|
|
|
public void reverse()
|
|
{
|
|
Node<T> curr = head;
|
|
|
|
if (curr == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Node<T> prev = null;
|
|
Node<T> next = curr.next;
|
|
while (next != null)
|
|
{
|
|
curr.next = prev;
|
|
prev = curr;
|
|
curr = next;
|
|
next = curr.next;
|
|
}
|
|
|
|
curr.next = prev;
|
|
head = curr;
|
|
}
|
|
|
|
@Override
|
|
public String toString()
|
|
{
|
|
return "[" + toStringInternal(head) + "]";
|
|
}
|
|
|
|
private String toStringInternal(Node<T> node)
|
|
{
|
|
if (node == null)
|
|
{
|
|
return "";
|
|
}
|
|
else if (node.next == null)
|
|
{
|
|
return node.value.toString();
|
|
}
|
|
else
|
|
{
|
|
return node.value + ", " + toStringInternal(node.next);
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args)
|
|
{
|
|
LinkedList<Integer> integers = new LinkedList<>(
|
|
new LinkedList.Node<>(1, new LinkedList.Node<>(2, new LinkedList.Node<>(3, null))));
|
|
System.out.println(integers);
|
|
|
|
integers.reverse();
|
|
System.out.println(integers);
|
|
}
|
|
}
|