一.类型和节点定义
用内部类的方式来定义链表的属性
public class SingleLinkList {
//头节点为空
private Node head = null;
private static class Node{
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
注意:这里的索引都是从1开始的,不是从0
二.头插法插入新节点
public void addFirst(int data){
Node p = head;
head = new Node(data,null);
head.next = p;
}
三.尾插法插入新节点
public void addLast(int data){
//先找到最后一个节点
Node p = head;
if(p == null){
addFirst(data);
return;
}
while ( p.next != null ){
p = p.next;
}
p.next = new Node(data,null);
}
四.遍历链表
public void printList(){
Node p = head;
while (p != null){
System.out.println(p.data);
p = p.next;
}
}
五.根据索引查找指定节点
public Node findIndex(int index){
Node p = head;
int i = 1;
while(p != null){
if(i == index){
return p;
}
i++;
p = p.next;
}
return null;
}
六.头部删除节点
public void removeFirst(){
if(head == null){
throw new IllegalArgumentException("头结点为空");
}
head = head.next;
}
七.根据索引删除指定位置的节点
public void remove(int index){
if(index == 1){
removeFirst();
return;
}
Node prev = findIndex(index - 1);
if(prev == null){
throw new IllegalArgumentException(String.format("参数不合法:%d",index));
}
Node removed = prev.next;
if(removed == null){
throw new IllegalArgumentException(String.format("参数不合法:%d",index));
}
prev.next = removed.next;
}