今天我们利用JAVA来实现一个单链表,
其中包括链表的结构,以及链表的基本操作。
整个类的设计:
public class Linked <T>{
private class Node{
private T t;
private Node next;
public Node(T t,Node next){
this.t = t;
this.next = next;
}
public Node(T t){
this(t,null);
}
}
private Node head; //头结点
private int size; //链表元素个数
//构造函数
public Linked(){
this.head = null;
this.size = 0;
}
}
常见的基本操作:
添加:
头插法:
public void addfirst(T t){
Node node = new Node(t);
node.next = this.head;
this.head = node;
this.size++;
}
尾插法:
public void addlist(T t){
this.add(t,this.size);
}
向链表中间插入元素:
public void add(T t,int index){
if(index < 0 || index > size){
throw new IllegalArgumentException("index is error");
}
if(index == 0){
this.addfirst(t);
return;
}
Node preNode = this.head; //找到要插入结点的位置;
for(int i = 0;i < index-1;i++){
preNode = preNode.next;
}
Node node = new Node(t);
node.next = preNode.next;
preNode.next = node;
this.size++;
}
删除:
public void remove(T t){
if(head == null){
System.out.println("无元素");
return;
}
while(head != null && head.t.equals(t)){//删除头元素
head = head.next;
this.size--;
}
Node del = this.head;
while(del != null && del.next != null){
if(del.next.t.equals(t)){
this.size--;
del.next = del.next.next;
}
else del = del.next;
}
}