LinkedList与链表

目录

1、链表

[1.1 链表的概念及结构](#1.1 链表的概念及结构)

[1.2 链表的实现](#1.2 链表的实现)

2、LinkedList的模拟实现

3、LinkedList的使用

[3.1 什么是LinkedList](#3.1 什么是LinkedList)

[3.2 LinkedList的使用](#3.2 LinkedList的使用)

[3.3 LinkedList的遍历](#3.3 LinkedList的遍历)

4、ArrayList和LinkedList的区别


在上一篇文章中,我们介绍了ArrayList与顺序表,ArrayList底层使用数组来存储元素,它是具有缺陷的。
ArrayList的缺陷:由于其底层是一段连续空间,当 ArrayList 任意位置插入或者删除元素时,就需要将后序元素整体往前或者往后 搬移,时间复杂度为 O(n) ,效率比较低,因此 ArrayList 不适合做任意位置插入和删除比较多的场景。因此:java集合中又引入了LinkedList,即链表结构。

1、链表

1.1 链表的概念及结构

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

  1. 单向或者双向
  1. 带头或者不带头
  1. 循环或者非循环

我们主要掌握以下两种结构:

  • 无头单向非循环链表 :结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。
  • 无头双向链表:在Java的集合框架库中LinkedList底层实现就是无头双向循环链表。

1.2 链表的实现

这里我们实现的是无头单向非循环链表:

java 复制代码
//无头单向非循环链表实现
public class MySingleList implements IList{

    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;

    public void CreateLinkedList() {
        ListNode node1 = new ListNode(10);
        ListNode node2 = new ListNode(20);
        ListNode node3 = new ListNode(30);
        ListNode node4 = new ListNode(40);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        this.head = node1;
    }
    @Override
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
        }else {
            node.next = this.head;
            this.head = node;
        }
    }

    @Override
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        ListNode cur = head;
        if (this.head == null) {
            this.head = node;
            return;
        }
        while (cur.next!=null) {
            cur = cur.next;
        }
        cur.next = node;
        node.next = null;
    }

    @Override
    public void addIndex(int index, int data) throws Indexillegal{
        if(index < 0||index > size()){
            //抛自定义异常
            throw new Indexillegal("插入下标异常:"+index);
        }
        if (index==0) {
            addFirst(data);
        }
        if (index == size()) {
            addLast(data);
        }
        ListNode node = new ListNode(data);
        ListNode cur = searchPre(index);
        node.next=cur.next;
        cur.next=node;

    }
    private ListNode searchPre(int index) {
        ListNode cur = head;
        int count = 0;
        while (count != index-1) {
            cur=cur.next;
            count++;
        }
        return cur;
    }
    @Override
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur!=null) {
            if (cur.val==key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        if (this.head == null){
            return;
        }
        if (this.head.val == key) {
            this.head=head.next;
            return;
        }
        ListNode cur = DelPrv(key);
        if (cur == null) {
            System.out.println("要删除的元素不存在");
        }else {
            ListNode del = cur.next;
            cur.next=del.next;
        }
    }
    private ListNode DelPrv(int key) {
        ListNode cur = head;
        while (cur.next!=null) {
            if (cur.next.val==key) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
    @Override
    public void removeAllKey(int key) {
        if (this.head == null) {
            return;
        }
        ListNode prv = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == key) {
                prv.next=cur.next;
                cur=cur.next;
            }else {
                prv = cur;
                cur = cur.next;
            }

        }
        if (this.head.val == key) {
            this.head=this.head.next;
        }
    }

    @Override
    public int size() {
        ListNode cur = head;
        int count = 0;
        while (cur!=null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    @Override
    public void clear() {
        ListNode cur = head;
        while (cur!=null) {
            ListNode curNext = cur.next;
            cur.next = null;
            cur = curNext;
        }
        head = null;
    }

    @Override
    public void display() {
        ListNode cur = head;
        while (cur!=null) {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }

    //从指定位置打印
    public void display(ListNode node) {
        ListNode cur = node;
        while (cur!=null) {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
}

其中自定义异常Indexillegal:

java 复制代码
public class Indexillegal extends RuntimeException{
    public Indexillegal(String msg) {
        super(msg);
    }
}

2、LinkedList 的模拟实现

LinkedList底层实现就是无头双向循环链表,所以下面是对无头双向链表的实现:

java 复制代码
//无头双向链表的实现
public class MyLinkedList implements IList{

    static class ListNode{
        public int val;
        public ListNode next;
        public ListNode prev;
        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode last;
    @Override
    public void addFirst(int data) {
        ListNode listNode = new ListNode(data);
        if (head == null) {
            head = listNode;
            last = listNode;
        }else {
            listNode.next = head;
            head.prev=listNode;
            head=listNode;
        }
    }

    @Override
    public void addLast(int data) {
        ListNode listNode = new ListNode(data);
        if (head == null){
            head = listNode;
            last = listNode;
        }else {
            last.next=listNode;
            listNode.prev=last;
            last = listNode;
        }
    }

    @Override
    public void addIndex(int index, int data) {
        int len = size();
        if (index < 0|| index > len) {
            System.out.println("插入异常");
            return;
        }
        if (index==0) {
            addFirst(data);
            return;
        }
        if (index==len) {
            addLast(data);
            return;
        }
        ListNode node = new ListNode(data);
        ListNode cur = FindIndex(index);
        node.next = cur;
        cur.prev.next = node;
        node.prev = cur.prev;
        cur.prev = node;
    }
    private ListNode FindIndex(int index) {
        ListNode cur = head;
        while (index != 0){
            cur = cur.next;
            index--;
        }
        return cur;
    }
    @Override
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur!=null) {
            if (cur.val==key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                if (cur == head) {
                    head = head.next;
                    if (head == null) {
                        last = null;
                    }else {
                        head.prev = null;
                    }
                }else {
                    cur.prev.next = cur.next;
                    if (cur.next == null) {
                        last = last.prev;
                    }else {
                        cur.next.prev = cur.prev;
                    }
                }
                return;
            }else {
                cur = cur.next;
            }
        }
    }

    @Override
    public void removeAllKey(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                if (cur == head) {
                    head = head.next;
                    if (head == null) {
                        last = null;
                    }else {
                        head.prev = null;
                    }
                }else {
                    cur.prev.next = cur.next;
                    if (cur.next == null) {
                        last = last.prev;
                    }else {
                        cur.next.prev = cur.prev;
                    }
                }
            }
            cur = cur.next;
        }
    }

    @Override
    public int size() {
        ListNode cur = head;
        int count = 0;
        while (cur!=null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    @Override
    public void clear() {
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = null;
            cur.prev = null;
            cur = curNext;
        }
        head = null;
        last = null;
    }

    @Override
    public void display() {
        ListNode cur = head;
        while (cur!=null) {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
}

3、LinkedList 的使用

3.1 什么是 LinkedList

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

在集合框架中,LinkedList也实现了List接口,具体如下:

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

3.2 LinkedList 的使用

  1. LinkedList 的构造

|------------------------------------------------|-------------------|
| 方法 | 解释 |
| LinkedList() | 无参构造 |
| public LinkedList(Collection<? extends E> c) | 使用其他集合容器中元素构造List |

代码示例:

java 复制代码
public static void main(String[] args) {
// 构造一个空的LinkedList
List<Integer> list1 = new LinkedList<>();
List<String> list2 = new java.util.ArrayList<>();
list2.add("JavaSE");
list2.add("JavaWeb");
list2.add("JavaEE");
// 使用ArrayList构造LinkedList
List<String> list3 = new LinkedList<>(list2);
}
  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<E> subList(int fromIndex, int toIndex) | 截取部分 list |

3.3 LinkedList的遍历

遍历方法有:foreach遍历和使用迭代器遍历

代码示例:

java 复制代码
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();
}

4、ArrayList LinkedList 的区别

|---------|----------------|----------------------|
| 不同点 | ArrayList | LinkedList |
| 存储空间上 | 物理上一定连续 | 逻辑上连续,但物理上不一定连续 |
| 随机访问 | 支持O(1) | 不支持:O(N) |
| 头插 | 需要搬移元素,效率低O(N) | 只需修改引用的指向,时间复杂度为O(1) |
| 插入 | 空间不够时需要扩容 | 没有容量的概念 |
| 应用场景 | 元素高效存储+频繁访问 | 任意位置插入和删除频繁 |

总结:以上就是对LinkedList和链表的总结了,注意它与ArrayList的区别,希望能帮到你们!

相关推荐
little redcap8 分钟前
第十九次CCF计算机软件能力认证-乔乔和牛牛逛超市
数据结构·c++·算法
Dola_Pan11 分钟前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book14 分钟前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
蜗牛^^O^1 小时前
Docker和K8S
java·docker·kubernetes
从心归零2 小时前
sshj使用代理连接服务器
java·服务器·sshj
IT毕设梦工厂3 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius3 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
七夜zippoe4 小时前
分布式系统实战经验
java·分布式
manba_4 小时前
leetcode-560. 和为 K 的子数组
数据结构·算法·leetcode
是梦终空4 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票