package com.wuhongyu.linkList;
public class LinkList<E> {
private class Node {
public E e;
public Node next;
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null, null);
}
@Override
public String toString(){
return e.toString();
}
}
private Node head = new Node();
private int size;
int getSize(){
return size;
}
boolean isEmpty(){
return size==0;
}
public void add(int index,E e){
if(index < 0 || index > size){
throw new IllegalArgumentException("输入下标错误");
}
add(head,index,e);
}
private void add(Node node ,int index,E e){
if(index == 0){
node.next = new Node(e,node.next);
return ;
}
add(node.next ,index--,e);
}
public void addFirst(E e){
add(0,e);
}
public void addLast(E e){
add(size,e);
}
public Node remove(int index){
if(index < 0 || index > size){
throw new IllegalArgumentException("输入下标错误");
}
return remove(index,head);
}
private Node remove(int index,Node node){
if(index == 0){
Node newNode = node.next;
node.next = newNode.next;
return newNode;
}
return remove(index--,node.next);
}
public Node removeFirst(){
return remove(0);
}
public Node removeLast(){
return remove(size);
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
Node cur = head.next;
while(cur != null){
res.append(cur + "->");
cur = cur.next;
}
res.append("NULL");
return res.toString();
}
}