什么是单链表?
单链表(Linked List):由各个内存结构通过一个next指针链接在一起组成,每一个内存结构都存在后继内存结构(链尾除外),内存结构由数据域和next指针域组成。
Data 数据 + Next 指针,组成一个单链表的内存结构 ;
第一个内存结构称为 链头,最后一个内存结构称为 链尾;
链尾的 Next 指针设置为 NULL [指向空];
单链表的遍历方向单一(只能从链头一直遍历到链尾)
插入:
在链表头部插入:
public void addHead(T t){
Node node = new Node(t);
node.next = this.head;
this.head = node;
this.linkedSize++;//链表长度增加
}
在链表中间插入:
public void add(T t, int index){
if(index<0 || index>linkedSize){
throw new IllegalArgumentException("下标错误");
}
if(index == 0){
this.addHead(t);
}
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.linkedSize++;
}
在链表尾部插入:
public void addTail(T t){
this.add(t, this.linkedSize);//尾部next直接指向一个新的元素
}
删除:
public void remove(T t){
if(head == null){
System.out.println("无元素可删除");
return;
}
if(!this.contains(t)){
System.out.println("数据不存在");
return;
}
while(head != null && head.t.equals(t)){
//删除的元素为头结点
head = head.next;
this.linkedSize--;
}
Node cur = this.head;
while(cur.next != null){
if(cur.next.t.equals(t)){
this.linkedSize--;
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
}
遍历链表:
//某元素是否在链表上
public boolean isExist(T t){
Node cur = this.head;
while(cur != null){
if(cur.t.equals(t)){
return true;
}
}
return false;
}