深圳幻海软件技术有限公司 欢迎您!

【数据结构与算法】LinkedList与链表

2023-04-02

✨个人主页:bitme✨当前专栏:数据结构✨每日一语:假如困境有解,何须心烦意乱;倘若困境无解,又何须郁郁寡欢。每个人都有两次生命,当你意识到你只有一次生命的时候,你的第二次生命就开始了🌹🌹🌹LinkedList与链表📕一.ArrayList的缺陷📗二.链表📄2.1链表的概念及结构📄2

✨个人主页:bit me
✨当前专栏:数据结构
✨每日一语:假如困境有解,何须心烦意乱;倘若困境无解,又何须郁郁寡欢。每个人都有两次生命,当你意识到你只有一次生命的时候,你的第二次生命就开始了🌹 🌹 🌹

LinkedList 与 链表

  • 📕一. ArrayList的缺陷
  • 📗二. 链表
    • 📄2.1 链表的概念及结构
    • 📄2.2 链表的实现
  • 📘三. LinkedList的模拟实现
  • 📒四.LinkedList的使用
    • 📜4.1 什么是LinkedList
    • 📜4.2 LinkedList的使用
  • 📔五. ArrayList和LinkedList的区别

 

📕一. ArrayList的缺陷

熟悉了ArrayList的使用后,并且进行了简单模拟实现。通过源码知道,ArrayList底层使用数组来存储元素,由于其底层是一段连续空间,当在ArrayList任意位置插入或者删除元素时,就需要将后序元素整体往前或者往后搬移,时间复杂度为O(n),效率比较低,因此ArrayList不适合做任意位置插入和删除比较多的场景。因此:java集合中又引入了LinkedList,即链表结构。

 

📗二. 链表

📄2.1 链表的概念及结构

链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。

 

注意:

  1. 从图中可以看出,链式结构在逻辑上是连续的,但是在物理上不一定连续
  2. 现实中的节点一般都是从堆上申请出来的
  3. 从堆上申请的空间,是按照一定的策略来分配的,两次申请的空间可能连续,也可能不连续

实际中链表的结构非常多样,以下情况组合起来就有8种链表结构:

  1. 单向或者双向

  2. 带头或者不带头

  3. 循环或者非循环

虽然有这么多的链表的结构,但是我们重点掌握两种:

  1. 无头单向非循环链表:结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。另外这种结构在笔试面试中出现很多。

  2. 无头双向链表:在Java的集合框架库中LinkedList底层实现就是无头双向循环链表。

📄2.2 链表的实现

  1. 链表是由一个一个节点组成的 就可以设置成内部类,然后就是定义数值域和存储下一个节点的地址,另外提供一个构造方法来new数值域
public class MySingleList {
static class ListNode{//静态内部类
    public int val;//数值域
    public ListNode next;//存储下一个节点的地址
    
    public ListNode(int val){
        this.val = val;
    }
}
...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

此处需要注意的是我们的构造方法只需要传val,因为我们next值是未知的,在任意位置都是不同的

  1. 定义单链表的头节点的引用
public ListNode head;
  • 1

注意在这里我们头节点不要定义在静态内部类中,头节点属于整个链表的头节点

  1. 进行初步简单的链表构造
public void creatList(){
    ListNode listNode1 = new ListNode(12);
    ListNode listNode2 = new ListNode(23);
    ListNode listNode3 = new ListNode(34);
    ListNode listNode4 = new ListNode(45);
    ListNode listNode5 = new ListNode(56);

    listNode1.next = listNode2;
    listNode2.next = listNode3;
    listNode3.next = listNode4;
    listNode4.next = listNode5;
    
    this.head = listNode1;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  1. 定义好一串链表数值val,此时next域为null
  2. 让每一个节点next域指向下一个节点,就发生了节点的链接指向
  3. 最后把第一个节点定义为头节点
  1. 链表的打印
public void display(){
    ListNode cur = head;
    while(cur != null){
        System.out.print(cur.val+" ");
        cur = cur.next;
    }
    System.out.println();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 在这里需要注意的是用cur替代head的遍历,head就会一直存在,不会被丢失掉
  2. cur替代head的时候,只要不为空,就一直打印然后往后走,直到为空后停止打印
  1. 查找是否包含关键字key,是否在单链表当中
public boolean contains(int key){
    ListNode cur = this.head;
    //cur != null 说明没有遍历完链表
    while(cur != null){
        if(cur.val == key){
            return true;
        }
        cur = cur.next;
    }
    return false;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

cur从头节点开始遍历,当头节点不为空的情况下,判断遍历的时候是否有元素和关键字key相等

  1. 得到单链表的长度
public int size(){
    int count = 0;
    ListNode cur = this.head;
    while(cur != null){
        count++;
        cur = cur.next;
    }
    return count;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

定义一个count,每当cur走一步,count就自增一次,直到cur遇到null然后返回count的值就是链表长度

  1. 头插法(时间复杂度O(1))
public void addFirst(int data){
    ListNode node = new ListNode(data);
    //当head == null的时候 可以直接总结出来
    /*if(this.head == null){
        this.head = node;
    }else{
        node.next = this.head;
        this.head = node;
    }*/
    node.next = this.head;
    this.head = node;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

定义一个node节点,让node节点next域指向head,然后把head赋值给node(注意顺序不可改变)

  1. 尾插法(时间复杂度O(n))
public void addLast(int data){
    ListNode node = new ListNode(data);
    if(head == null){
        head = node;
    }else{
        ListNode cur = head;
        while(cur.next != null){
            cur = cur.next;
        }
        //cur.next == null;
        cur.next = node;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

当cur遍历走到null的位置时,说明走到了最后一个节点的位置,此时让cur的next域指向node就可以把node插入到尾部节点

  1. 指定位置插入元素,为了插入元素,我们得先给每个节点赋予下标

①:先判断下标合法性

private void checkIndexAdd(int index){
    if (index < 0 || index > size()){
        throw new MySingleListIndexOutOfException("任意位置插入的时候,index位置不合法!");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5

下标既不能是0,也不能大于链表长度,否则是不合法的

②:考虑特殊情况,下标为0插入相当于头插法,下标为链表长度为尾插法
③:如何插入元素?

例如在下标为 1 和 2 之间插入元素,插入节点为node,我们让cur走到1的时候,让node的next指向cur的next,就相当于让node的next指向了下标为2的节点,再让cur的next指向node就可以把三者连接起来了

找到node前一个节点的位置cur

private ListNode findIndexSubOne(int index){
    ListNode cur = this.head;
    while (index - 1 != 0){
        cur = cur.next;
        index--;//cur走的趟数
    }
    return cur;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

总的实现:

public void addIndex(int index,int data){
    checkIndexAdd(index);
    if(index == 0){
        addFirst(data);
        return;
    }
    if(index == size()){
        addLast(data);
        return;
    }
    ListNode node = new ListNode(data);
    ListNode cur = findIndexSubOne(index);
    node.next = cur.next;
    cur.next = node;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  1. 删除第一次出现的关键字key

删除一个节点我们可以让关键字key前面的一个节点直接指向关键字key后面一个节点,直接跳过了key就是删除了

public void remove(int key){
    if(this.head == null){
        System.out.println("此时链表为空,不能进行删除!");
        return;
    }
    if(this.head.val == key){
        //判断第一个节点是不是等于我要删除的节点
        this.head = this.head.next;
        return;
    }

    ListNode cur = this.head;
    while(cur.next != null){
        if(cur.next.val == key){
            //进行删除了
            ListNode del = cur.next;
            cur.next = del.next;
            return;
        }
        cur = cur.next;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  1. 考虑特殊情况,链表为空和第一个节点就是我们要删除的关键字
  2. 首先在cur的next域不为空的前提下我们才能判断cur的next域的val,不至于发生空指针异常,当我们cur的next的val为关键字的时候,最终目的就是要让cur的next往后指俩位,相当于cur.next.next,直接逃过要删除的节点就可以了
  1. 删除所有值为key的节点

要求:

  1. 时间复杂度为O(n)
  2. 只遍历单链表一遍

首先我们需要知道的是:

删除的核心是 需要找到这个节点的前一个节点是谁

所以我们在这里定两个指针cur和prev,其中cur代表的是要删除的节点,prev代表的是cur的前驱

每次cur走一步的时候,prev都会紧随其后,当cur遇到了要删除的链表,都会直接往后走,直到遇到非val值的节点,然后prev继续跟着cur走

①:先考虑特殊情况:头节点不为空
②:定义cur和prev指针位置
③:在删除节点之前,我们得知道cur走动的前提是不为空的
④:在cur 不为空的前提下,我们该如何删除元素呢?

如第二个节点为我们要删除的元素,直接让prev(head)指向第三个元素的下标,第三个元素的下标就是cur.next,所以最终的式子就是prev.next = cur.next,然后让cur继续往后面走,继续执行此代码

⑤:最终代码就完成了,但是还有一个特殊情况,那就是cur是从第二个元素开始遍历,并没有考虑到头节点,所以我们在这里单独判断一下头节点

public void removeAllKey(int key){
   //删除的核心是需要找到这个节点的前一个节点是谁   设置prev为cur的前一个节点
   if(this.head == null){
       return;
   }
   ListNode cur = this.head.next;
   ListNode prev = this.head;

   while(cur != null){
       if(cur.val == key){
           prev.next = cur.next;
           cur = cur.next;
       }else{
           prev = cur;
           cur = cur.next;
       }
   }
   //单独处理了头节点
   if(this.head.val == key){
       head = head.next;
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  1. 清空链表里的所有元素

就是每个节点之间 不要有人引用了

①:方法一:暴力直接一步到位就是直接把头节点置为空,这样后面的链式节点全都没人引用了
②:方法二:让curNext为空,cur遍历的时候,把curNext赋给cur,最后单独处理下头节点

public void clear(){
    //this.head = null;//一步到位 暴力直接
    ListNode cur = this.head;
    ListNode curNext = null;
    while(cur != null){
        curNext = cur.next;
        cur.next = null;
        cur = curNext;
    }
    head = null;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

 

📘三. LinkedList的模拟实现

LinkedList底层就是一个双向链表,我们来实现一个双向链表。

  1. 它是由一个一个节点组成的 就可以设置成内部类,然后就是定义数值域,储存上一个节点的地址和存储下一个节点的地址,另外提供一个构造方法来new数值域
static class ListNode{
    public int val;
    public ListNode prev;
    public ListNode next;

    public ListNode(int val){//此处不添加prev和next参数是因为实例化节点的时候前后都是未知的
        this.val = val;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. 标记头尾节点
public ListNode head;//标记头部
public ListNode last;//标记尾部
  • 1
  • 2
  1. 打印
public void display(){
    ListNode cur = head;
    while(cur != null){
        System.out.print(cur.val+" ");
        cur = cur.next;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

和链表一样的打印

  1. 头插法
public void addFirst(int data){
    ListNode node = new ListNode(data);
    if(head == null){
        head = node;
        last = node;
    }else{
        node.next = head;
        head.prev = node;
        head = node;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 考虑特殊情况,LinkedList为空的情况下
  2. 如何头插:插入节点的next域引用头节点,头节点的前一节点域指向node,然后node就成为了头节点
  1. 尾插法
public void addLast(int data){
    ListNode node = new ListNode(data);
    if(head == null){
        head = node;
        last = node;
    }else{
        last.next = node;
        node.prev = last;
        last = node;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 考虑特殊情况,LinkedList为空的情况下
  2. 让最后节点的next域引用node,然后把node的前缀指向最后的节点,让最后的节点等于node
  1. 得到单链表的长度
public int size(){
    int count = 0;
    ListNode cur = head;
    while(cur != null){
        count++;
        cur = cur.next;
    }
    return count;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. 在任意位置插入节点

①:首先我们得定义下标,为节点插入做准备

private ListNode searchIndex(int index){
    ListNode cur = head;
    while(index != 0){
        cur = cur.next;
        index--;
    }
    return cur;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

②:插入方法实现

cur是插入节点后一位的节点,让node的next域指向cur,再让插入节点前一位节点的next域指向node,让node的prev域指向插入节点的前一位节点,最后把cur的prev域指向node就完成了所有的步骤

public void addIndex(int index,int data){
    if(index < 0 || index > 0){
        System.out.println("index不合法!");
    }
    if(index == 0){
        addFirst(data);
        return;
    }
    if(index > size()){
        addLast(data);
        return;
    }
    //cur拿到了index下标的节点的地址
    ListNode cur = searchIndex(index);
    ListNode node = new ListNode(data);
    node.next = cur;
    cur.prev.next = node;
    node.prev = cur.prev;
    cur.prev = node;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  1. 查找是否包含关键字key是否在单链表当中
public boolean contains(int key){
    ListNode cur = head;
    while(cur != null){
        if(cur.val == key){
            return true;
        }
        cur = cur.next;
    }
    return false;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 删除第一次出现关键字为key的节点
public void remove(int key){
    ListNode cur = head;
    while(cur != null){
        if(cur.val == key){
            //判断当前是不是头节点
            if(cur == head){
                head = head.next;
                if(head != null){//只有一个节点
                        head.prev = null;
                    }
            }else {
                //中间和尾巴的情况
                cur.prev.next = cur.next;
                if(cur.next != null){
                    cur.next.prev = cur.prev;
                }else {
                    last = last.prev;
                }
            }
            return;
        }else {
            cur = cur.next;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. 在这里我们删除节点不需要额外的前驱信息,节点本身就包含了
  2. 删除的条件cur.prev.next = cur.next; cur.next.prev = cur.prev;
  3. 在这里面我们用了前驱后驱信息,考虑特殊情况是有头节点和尾节点的,所以我们又要分开考虑
  4. 头节点就直接往后走,记得前驱为空,且考虑只有一个节点的情况
  5. 尾节点就直接往前面走
     
    注意:判断后如果没有return,删除前面的节点就可能发生空指针异常
  1. 删除所有值为key的节点

和单个的删除是一样的,只是判断完了之后我们需要让cur继续走就对了,此时不可以return

public void removeAllKey(int key){
    ListNode cur = head;
    while(cur != null){
        if(cur.val == key){
            //判断当前是不是头节点
            if(cur == head){
                head = head.next;
                if(head != null){
                    head.prev = null;
                }
            }else {
                //中间和尾巴的情况
                cur.prev.next = cur.next;
                if(cur.next != null){
                    cur.next.prev = cur.prev;
                }else {
                    last = last.prev;
                }
            }
            cur = cur.next;//继续往后走
        }else {
            cur = cur.next;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. 清空链表

遍历置为空就可以

public void clear(){
    ListNode cur = head;
    while(cur != null){
        ListNode curNext = cur.next;
        //cur.val = null  是引用类型就置为空,基本类型就不用
        cur.prev = null;
        cur.next = null;
        cur = curNext;
    }
    head = null;
    last = null;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

需要注意的是这里头节点和尾节点需要置为空,因为遍历完成之后他们还在被引用

 

📒四.LinkedList的使用

📜4.1 什么是LinkedList

LinkedList的底层是双向链表结构(链表后面介绍),由于链表没有将元素存储在连续的空间中,元素存储在单独的节点中,然后通过引用将节点连接起来了,因此在在任意位置插入或者删除元素时,不需要搬移元素,效率比较高。
 

在集合框架中,LinkedList也实现了List接口

说明:

  1. LinkedList实现了List接口
  2. LinkedList的底层使用了双向链表
  3. LinkedList没有实现RandomAccess接口,因此LinkedList不支持随机访问
  4. LinkedList的任意位置插入和删除元素时效率比较高,时间复杂度为O(1)

📜4.2 LinkedList的使用

  1. LinkedList的构造
方法解释
LinkedList()无参构造
public LinkedList(Collection<? extends E> c)使用其他集合容器中元素构造List
  1. LinkedList的其他常用方法介绍
方法解释
boolean add(E e)尾插 e
void add(int index, E element)将 e 插入到 index 位置
boolean addAll(Collection<? extends E> c)尾插 c 中的元素
E remove(int index)删除 index 位置元素
boolean remove(Object o)删除遇到的第一个 o
E get(int index)获取下标 index 位置元素
E set(int index, E element)将下标 index 位置元素设置为 element
void clear()清空
boolean contains(Object o)判断 o 是否在线性表中
int indexOf(Object o)返回第一个 o 所在下标
int lastIndexOf(Object o)返回最后一个 o 的下标
List subList(int fromIndex, int toIndex)截取部分 list

方法简介:

public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1); // add(elem): 表示尾插
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
System.out.println(list.size());
System.out.println(list);
// 在起始位置插入0
list.add(0, 0); // add(index, elem): 在index位置插入元素elem
System.out.println(list);
list.remove(); // remove(): 删除第一个元素,内部调用的是removeFirst()
list.removeFirst(); // removeFirst(): 删除第一个元素
list.removeLast(); // removeLast(): 删除最后元素
list.remove(1); // remove(index): 删除index位置的元素
System.out.println(list);
// contains(elem): 检测elem元素是否存在,如果存在返回true,否则返回false
if(!list.contains(1)){
list.add(0, 1);
}
list.add(1);
System.out.println(list);
System.out.println(list.indexOf(1)); // indexOf(elem): 从前往后找到第一个elem的位置
System.out.println(list.lastIndexOf(1)); // lastIndexOf(elem): 从后往前找第一个1的位置
int elem = list.get(0); // get(index): 获取指定位置元素
list.set(0, 100); // set(index, elem): 将index位置的元素设置为elem
System.out.println(list);
// subList(from, to): 用list中[from, to)之间的元素构造一个新的LinkedList返回
List<Integer> copy = list.subList(0, 3); 
System.out.println(list);
System.out.println(copy);
list.clear(); // 将list中元素清空
System.out.println(list.size());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  1. LinkedList的遍历
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1); // add(elem): 表示尾插
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
System.out.println(list.size());
// foreach遍历
for (int e:list) {
System.out.print(e + " ");
}
System.out.println();
// 使用迭代器遍历---正向遍历
ListIterator<Integer> it = list.listIterator();
while(it.hasNext()){
System.out.print(it.next()+ " ");
}
System.out.println();
// 使用反向迭代器---反向遍历
ListIterator<Integer> rit = list.listIterator(list.size());
while (rit.hasPrevious()){
System.out.print(rit.previous() +" ");
}
System.out.println();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

 

📔五. ArrayList和LinkedList的区别

ArrayListLinkedList
存储空间上 物理上一定连续逻辑上连续,但物理上不一定连续
随机访问 支持O(1)随机访问 不支持:O(N)
头插 需要搬移元素,效率低O(N)头插 只需修改引用的指向,时间复杂度为O(1)
插入 空间不够时需要扩容没有容量的概念
应用场景:元素高效存储+频繁访问任意位置插入和删除频繁
文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览42750 人正在系统学习中