public class ListNode<T>{
T val;
private ListNode<T> next;
private int size = -1; //未插入时 为 -1
public ListNode(){size = -1;} //虚拟节点
//设置为private 不给外界创建一个带有值的头结点,造成误解 这个私有构造函数在add方法中使用
private ListNode(T val){ //虚拟节点
this.val = val;
size = -1;
}
public void add(T val){
size++;
ListNode<T> head = this;
while(head.next != null){
head = head.next;
}
head.next = new ListNode<T>(val);
}
//得到投节点 以及 得到指定下标节点
public ListNode<T> get(){
//return this.next;
return get(0);
}
public ListNode<T> get(int index){//index = 0
if(index > size || index < 0){
throw new RuntimeException("下标越界");
}
ListNode<T> cur = this;
while(index >= 0){
cur = cur.next;
index --;
}
return cur;
}
//得到投节点的值 以及 得到指定下标节点的值
public T getVal(){
//return this.val;
return getVal(0);
}
public T getVal(int index){
if(index > size){
throw new RuntimeException("下标越界");
}
ListNode<T> head = this;
while(index >= 0){
head = head.next;
index --;
}
return head.val;
}
//删除头节点 删除指定节点 并返回删除的节点
public ListNode<T> remove(){//删除头节点
return remove(0);
}
public ListNode<T> remove(int index){
if(index > size){
throw new RuntimeException("下标越界");
}
ListNode<T> head = this;
ListNode<T> cur = this;
while(index >= 0){
head = cur;
cur = cur.next;
index --;
}
head.next = cur.next;
size --;
return cur;
}
//修改指定下标位置的节点值
public void update(int index, T val){
ListNode<T> cur = get(index);
cur.val = val;
}
//获得当前链表的长度
public int size(){
if(size == -1){
throw new RuntimeException("当前链表为空");
}
return size + 1;
}
}