//Node构造方法
public class Node<T> {
Node<T> next;
T value;
public Node(Node<T> next,T value){
this.next = next;
this.value = value;
}
}
/**
* 链表:头插、尾插,删除
* @param <T> 类型
*/
public class Link<T> {
private Node<T> head = null;
private Node<T> tail = null;
public void add(T value){ //头插
Node<T> n = new Node<T>(null,value); //创建一个结点,next为空
if(head == null){ //如果没有数据,则头节点、尾节点 = 这个节点;
head = tail = n;
}else{
n.next = head; //有数据,先把n的next给head,head再指向n
head = n;
}
}
public void append(T value) { //尾插
Node<T> n = new Node<T>(null, value); //创建一个新节点n
if (tail != null) { //有数据,
tail.next = n; //则最后一个的next = n
tail = n; // tail指向n
} else {
head = tail = n; //无数据,head = tail = n
}
}
public void delete(int index){
Node<T> temp = head;
if(index == 0){ //删除第一个,head直接后移一位
head = head.next;
return;
}
for(int i = 0;i < index - 1;i++,temp = temp.next){ //把temp定位到删除元素的前一个元素
if(temp.next == null){ //越界异常
throw new IndexOutOfBoundsException();
}
}
if(temp.next == tail){ //如果删除的元素为最后一个,则移动tail到删除元素前一个元素即为temp
tail = temp;
}
temp.next =temp.next.next; //删除的为中间元素,则temp= temp.next.next
}
@Override
public String toString(){ //链表元素放入s,再输出
StringBuilder s = new StringBuilder();
if(head != null){
for(Node<T> temp = head; temp != null;temp = temp.next){
if(s.length() > 0){
s.append(",");
}
s.append(temp.value);
}
}
return s.toString();
}
//main方法
public static void main(String[] args){
Link<Integer> link = new Link<>();
link.add(50);
link.append(20);
link.append(30);
link.append(40);
link.delete(2);
System.out.println(link);
}
}