package thread.juc.linkedlist;
import java.util.NoSuchElementException;
public class SortLinkedList<E extends Comparable<E>> {
private Node<E> head = null;
private int size;
public SortLinkedList() {
head = null;
}
class Node<E extends Comparable<E>> {
Node<E> next;
E value;
public Node(E value) {
this.value = value;
}
public Node() {
}
}
public void addFirst(E e) {
Node<E> newNode = new Node<E>(e);
Node<E> previous = null;
Node<E> current = head;
while (current != null && e.compareTo(current.value) > 0) {
previous = current;
current = current.next;
}
if (previous == null) {
head = newNode;
} else {
previous.next = newNode;
}
newNode.next = current;
size++;
}
public Node<E> removeFirst() {
if (size == 0) {
throw new NoSuchElementException("linkList is empty ... ");
}
size--;
Node<E> node = this.head;
this.head = node.next;
return node;
}
public boolean isEmpty() {
return size == 0;
}
public String toString() {
if (this.size == 0) {
return "[]";
}
Node<E> node = head;
StringBuilder builder = new StringBuilder("[");
while (node != null) {
System.out.println(node.value);
builder.append(node.value).append(",");
node = node.next;
}
String sb = builder.toString().substring(0, builder.length() - 1) + "]";
return sb;
}
public int size() {
return size;
}
public boolean contains(E e) {
Node<E> head = this.head;
while (head != null) {
if (head.value.equals(e)) {
return true;
}
head = head.next;
}
return false;
}
public static void main(String[] args) {
SortLinkedList<Integer> list = new SortLinkedList<>();
list.addFirst(2);
list.addFirst(-1);
list.addFirst(-20);
list.addFirst(200);
list.addFirst(5);
list.addFirst(7);
System.out.println(list.isEmpty());
System.out.println(list.size());
System.out.println(list.toString());
System.out.println(list.contains(1));
}
}