package thread.juc.linkedlist;
import java.util.NoSuchElementException;
public class LinkedList<E> {
private Node<E> head = null;
private int size;
public LinkedList() {
head = null;
}
class Node<E> {
Node<E> next;
E value;
public Node(E value) {
this.value = value;
}
public Node() {
}
}
public void addFirst(E e) {
Node<E> node = new Node<E>(e);
node.next = head;
head = node;
size++;
}
public void addLast(E e) {
if (head == null) {
head = new Node<>();
}
Node<E> node0 = head;
Node<E> newNode = new Node<E>(e);
if (node0 == null) {
head = newNode;
} else {
node0.next = newNode;
}
size++;
}
public boolean remove(E e) {
Node<E> current = head;
if (current.value.equals(e)){
head = current.next;
return true;
}
Node<E> previous = null;
while (current != null) {
if (current.value.equals(e)) {
previous.next = current.next;
return true;
}
previous = current;
current = current.next;
}
return false;
}
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) {
LinkedList<String> list = new LinkedList<>();
list.addFirst("张三1");
list.addFirst("张三2");
list.addFirst("张三3");
list.addFirst("张三4");
list.addFirst("张三5");
list.addFirst("张三6");
System.out.println(list.isEmpty());
System.out.println(list.size());
System.out.println(list.toString());
System.out.println(list.contains("张三1"));
System.out.println(" ============ rmove ========= ");
list.remove("张三4");
System.out.println(list.toString());
list.remove("张三1");
System.out.println(list.toString());
list.remove("张三6");
System.out.println(list.toString());
}
}