package LinkedList;
//节点
class SingleNode{
Object data;//数据
SingleNode next;//下一节点
public SingleNode() {}
public SingleNode(Object data){
this.data = data;
}
}
//单链表
class SingleLinkedList{
SingleNode head = null;//头节点,不放数据,真正的数据从head.next开始
SingleNode tail = null;//尾节点,链表的最后一个节点
public SingleLinkedList(){
this.head = tail = new SingleNode();
}
//获取索引为index-1的节点,索引index从1开始
public SingleNode getNodeByIndex(int index){
SingleNode n = head.next;
int i = 1;
//如果索引是1,则代表要第一个节点也就是head.next,而head.next的index-1节点就是head节点
if(index == 1) return head;
if(index < 1) return null;
while(n != null){
//返回节点
if(i == index - 1) return n;
n = n.next;
i++;
}
return null;
}
public void add(Object data){
SingleNode n = new SingleNode(data);
tail.next = n;
tail = n;
}
public void add(Object data,int index){
SingleNode n = new SingleNode(data);
SingleNode tmp = getNodeByIndex(index);//获取index的上一个节点
if(tmp == null || tmp.next == null){System.out.println("index is not,add error");return;}
n.next = tmp.next;
tmp.next = n;
}
public void delete(){
SingleNode n = head.next;
while(n != null){
SingleNode tmp = n;//保留前一个节点
n = n.next;
if(n == null){//只有一个节点,直接删除第一个节点
//这里直接重置了head和tail节点
this.head = tail = new SingleNode();
return;
}
if(n.next == null){//n.next等于空,代表n是最后一个节点,删除n
tmp.next = null;
tail = tmp;
return;
}
}
}
public void delete(int index){
SingleNode tmp = getNodeByIndex(index);
if(tmp == null || tmp.next == null){System.out.println("index is not,delete error");return;}
tmp.next = null;
tail = tmp;
}
public void update(Object data){
tail.data = data;
}
public void update(int index,Object data){
SingleNode tmp = getNodeByIndex(index);
if(tmp == null || tmp.next == null){System.out.println("index is not,update error");return;}
tmp.next.data = data;
}
public void print(){
SingleNode n = head.next;
while(n != null){
System.out.print(n.data+" ");
n = n.next;
}
System.out.println("");
}
}
public class SingleLinkedListDemo {
public static void main(String[] args) {
SingleLinkedList sll = new SingleLinkedList();
sll.add(1);
sll.add(2);
sll.add(5, 3);
sll.print();
sll.delete();
sll.print();
sll.delete(0);
sll.print();
sll.update(2);
sll.add(3);
sll.add(4);
sll.add(5);
sll.print();
sll.update(3, 55);
sll.print();
}
}
结果: