package com.thread.utils.collections;
public class LinkedList<E> {
private int size;
private Node<E> first;
private final String PLAIN_NULL = "null";
private final Node<E> NULL = (Node<E>) null;
public LinkedList() {
this.first = NULL;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public void addFirst(E e) {
Node<E> node = new Node<>(e);
node.next = first;
first = node;
size++;
}
public static <E> LinkedList<E> of(E... elements) {
LinkedList<E> list = new LinkedList<>();
if (elements.length > 0) {
for (E e : elements) {
list.addFirst(e);
}
}
return list;
}
public boolean contains(E e) {
Node<E> current = first;
while (current != null) {
if (current.value == e) {
return true;
}
current = current.next;
}
return false;
}
public E removeFirst() {
if (this.isEmpty()) throw new RuntimeException("no such elements");
Node<E> node = first;
first = node.next;
size--;
return node.value;
}
public LinkedList<E> addLast(E e) {
Node<E> node = new Node<>(e);
node.next = NULL;
return this;
}
private static class Node<E> {
E value;
Node<E> next;
public Node(E value) {
this.value = value;
}
@Override
public String toString() {
if (null != value)
return value.toString();
return "null";
}
}
@Override
public String toString() {
if (this.isEmpty()) return "[]";
else {
StringBuilder builder = new StringBuilder("[");
Node<E> node = first;
while (node != null) {
builder.append(node.toString()).append(",");
node = node.next;
}
builder.replace(builder.length() - 1, builder.length(), "]");
return builder.toString();
}
}
public static void main(String[] args) {
LinkedList<String> list = LinkedList.of("Hello", "World", "Scala", "Java", "Thread");
list.addFirst("Concurrentcy");
System.out.println(list.size);
System.out.println(list.contains("Java"));
System.out.println(list);
while (!list.isEmpty()) {
System.out.println(list.removeFirst());
}
System.out.println(list.size);
System.out.println(list.isEmpty());
}
}