Java数据结构-LinkedList与链表

本文详细介绍了Java中的链表(ArrayList和LinkedList)概念、结构、实现以及它们在插入、删除操作上的性能差异,重点讲解了单链表和双向链表,并探讨了LinkedList在集合框架中的适用场景。
摘要由CSDN通过智能技术生成


前言

本文用于对最近学习的Java中链表知识进行总结。


一、链表

1.1 ArrayList的缺陷

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

1.2 链表的概念及结构

链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。
在这里插入图片描述
实际中链表的结构非常多样,以下情况组合起来就有8种链表结构:
(1)单向或者双向
在这里插入图片描述
(2)带头或者不带头
在这里插入图片描述
(3)循环或者非循环
在这里插入图片描述

重点掌握两种:
  无头单向非循环链表.
  无头双向链表:在Java的集合框架库中LinkedList底层实现就是无头双向循环链表。

1.3 单链表的实现

public class MySingleList {

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

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

    public ListNode head;

    public void createList() {
        ListNode node1 = new ListNode(12);
        ListNode node2 = new ListNode(12);
        ListNode node3 = new ListNode(12);
        ListNode node4 = new ListNode(12);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        head = node1;
    }

    //头插法
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        ListNode cur = head;
        if (head == null) {
            head = node;
        } else {
            while (cur.next != null) {
                cur = cur.next;

            }
            cur.next = node;

        }
    }

    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index, int data) {
        ListNode node = new ListNode(data);
        checkIndexAdd(index);
        if (index == 0) {
            addFirst(data);
            return true;
        }
        if (index == size()) {
            addLast(data);
        }
        int count = 0;
        ListNode cur = head;
        while (count != index - 1) {
            cur = cur.next;
        }
        node.next = cur.next;
        cur.next = node;
        return true;
    }

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

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;

    }

    //删除第一次出现关键字为key的节点
    public void remove(int key) {
        if (head == null) {
            return;
        }
        if (head.val == key) {
            head = head.next;
            return;
        }

        ListNode cur = head;
        while (cur.next != null) {
            if (cur.next.val == key) {
                ListNode del = cur.next;
                cur.next = del.next;
                return;
            }
            cur = cur.next;


        }

    }

    //删除所有值为key的节点
    public void removeAllKey(int key) {
        if (head == null) {
            return;
        }

        ListNode pre = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == key) {

                pre.next = cur.next;
                cur = cur.next;

            } else {
                pre = cur;
                cur = cur.next;

            }


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

    //得到单链表的长度
    public int size() {
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            len++;
        }
        return len;
    }

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

    /**
     * 从指定节点开始打印
     */
    public void display(ListNode newHead) {

        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + "");
            cur = cur.next;
        }
        System.out.println();
    }

    public void clear() {
//        head=null;
        ListNode cur = head;
        ListNode temp;
        while (cur != null) {
            temp = cur.next;
            cur.next = null;
            cur = temp;
        }
        head = null;
    }
}

1.4 双向链表的实现

public class MyLinkedList {
    private static class ListNode {
        int val;
        ListNode next;
        ListNode pre;

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

    ListNode head;
    ListNode last;

    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if (head == null) {
            head = node;
            last = node;
        } else {
            node.next = head;
            head.pre = node;
            head = node;
        }
    }

    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if (head == null) {
            head = node;
            last = node;
        } else {
            last.next = node;
            node.pre = last;
            last = node;
        }
    }

    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index, int data) {

        if (index < 0 || index > size()) {
            throw new IndexOutException("index:" + index);
        }
        if (index == 0) {
            addFirst(data);
            return;
        }
        if (index == size()) {
            addLast(data);
            return;
        }
        ListNode node = new ListNode(data);
        ListNode cur = head;
        while (index != 0) {
            cur = cur.next;
            index--;
        }

        node.next = cur;
        node.pre = cur.pre;
        cur.pre.next = node;
        cur.pre = node;
    }

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    //删除第一次出现关键字为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.pre = null;
                    } else {
                        last = null;
                    }
                } else {
                    //删除中间节点
                    cur.pre.next = cur.next;
                    //后一个节点是否为最后一个节点
                    if (cur.next != null) {
                        cur.next.pre = cur.pre;
                    } else {
                        last = last.pre;
                    }
                }
                return;
            }
            cur = cur.next;

        }


    }

    //删除所有值为key的节点
    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.pre = null;
                    } else {
                        last = null;
                    }
                } else {
                    //删除中间节点
                    cur.pre.next = cur.next;
                    //后一个节点是否为最后一个节点
                    if (cur.next != null) {
                        cur.next.pre = cur.pre;
                    } else {
                        last = last.pre;
                    }
                }

            }
            cur = cur.next;

        }
    }

    //得到单链表的长度
    public int size() {
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        return len;
    }

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

    public void clear() {
//        this.head=null;
//        this.last=null;
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.pre = null;
            cur.next = null;
            cur = curNext;
        }
        head = null;
        last = null;
    }
}

二、LinkedList的使用

2.1 什么是LinkedList

LinkedList的底层是双向链表结构,由于链表没有将元素存储在连续的空间中,元素存储在单独的节点中,然后通过引用将节点连接起来了,因此在在任意位置插入或者删除元素时,不需要搬移元素,效率比较高。
在集合框架中,LinkedList也实现了List接口,具体如下:
在这里插入图片描述

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

2.2 LinkedList的使用

(1)LinkedList的构造
在这里插入图片描述
代码示例如下:

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);
}

(2) 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());
    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());
}

(3)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();
}

三、ArrayList和LinkedList的区别

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值