数据结构(四)LinkedList

一、ArrayList的缺陷

通过源码知道,ArrayList底层使用数组来存储元素:

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    // ...
    // 默认容量是10
    private static final int DEFAULT_CAPACITY = 10;
    //...
    // 数组:用来存储元素
    transient Object[] elementData; // non-private to simplify nested class access
    // 有效元素个数
    private int size;
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
            initialCapacity);
        }
    }
    // ...
}

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

二、LinkedList的使用

什么是LinkedList

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

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

【说明】

1. LinkedList实现了List接口

2. LinkedList的底层使用了双向链表

3. LinkedList没有实现RandomAccess接口,因此LinkedList不支持随机访问

4. LinkedList的任意位置插入和删除元素时效率比较高,时间复杂度为O(1)

LinkedList的使用

LinkedList的构造

方法

解释

LinkedList()

无参构造

public LinkedList(Collection<? extends E> c)

使用其他集合容器中元素构造List

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

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

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

三、链表

链表的概念及结构

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

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

1. 单向或者双向

2. 带头或者不带头

3. 循环或者非循环

重点掌握:

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

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

链表的实现

无头单向非循环链表实现

class ListNode {
    public int val;
    public ListNode next;

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

public class SingleLinkedList {

    public ListNode head;
    public int usedSize;
    public void createList(){
        ListNode node1=new ListNode(12);
        ListNode node2=new ListNode(23);
        ListNode node3=new ListNode(34);
        ListNode node4=new ListNode(45);
        ListNode node5=new ListNode(56);

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

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

    //头插法
    public void addFirst(int data){
        ListNode node=new ListNode(data);
        if (head==null){
            this.head=node;
        }else {
            node.next=head;
            head=node;
        }
        this.usedSize++;
    }
    //尾插法
    public void addLast(int data){
        ListNode node=new ListNode(data);
        if (this.head==null){
            this.head=node;
        }else {
            ListNode cur=this.head;
            while (cur.next!=null){
                cur=cur.next;
            }
            cur.next=node;
        }
        this.usedSize++;
    }
    //查找Index-1位置的节点的地址
    private ListNode searchIndex(int index){
        int count=0;
        ListNode cur=this.head;
        while (count!=index-1){
            cur=cur.next;
            count++;
        }
        return cur;
    }
    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data) {
        if (index<0||index>this.usedSize){
            throw new RuntimeException("index不合法");
        }
        if(index==0){
            addFirst(data);
            return;
        }
        if (index==this.usedSize){
            addLast(data);
            return;
        }
        ListNode node=new ListNode(data);
        ListNode cur=searchIndex(index);
        node.next=cur.next;
        cur.next=node;
        this.usedSize++;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        ListNode cur=this.head;
        while (cur!=null){
            if (cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //找到key的前一个节点
    private ListNode findPrevNode(int key){
        ListNode prev=this.head;
        while (prev.next!=null){
            if (prev.next.val==key){
                return prev;
            }
            prev=prev.next;
        }
        return null;
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){
        if (this.head==null){
            return;
        }
        if (this.head.val==key) {
            this.head = this.head.next;
            return;
        }
        ListNode prev=findPrevNode(key);
        if (prev==null){
            throw new RuntimeException("不存在要删除的节点");
        }
        ListNode del=prev.next;
        prev.next=del.next;
        this.usedSize--;
    }
    //删除所有值为key的节点
    public void removeAllKey(int key) {
        if (this.head==null){
            return;
        }
        ListNode prev=this.head;
        ListNode cur=prev.next;
        while (cur!=null){
            if (cur.val==key){
                prev.next=cur.next;
                cur=cur.next;
                this.usedSize--;
            }else {
                prev=cur;
                cur=cur.next;
            }
        }
        if (this.head.val==key){
            this.head=this.head.next;
            this.usedSize--;
        }
    }
    //得到单链表的长度
    public int size(){
        ListNode cur=this.head;
        int i=0;
        while (cur!=null){
            cur=cur.next;
            i++;
        }
        return i;
    }
    public void clear(){
        this.head=null;
        this.usedSize=0;
    }
}

无头双向链表实现

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

    public ListNode(int val) {
        this.val = val;
    }
}
public class MyLinkedList {
    public ListNode head;
    public ListNode last;//标记双向链表的尾巴

    //头插法
    public void addFirst(int data) {
        ListNode node=new ListNode(data);
        if (this.head==null){
            this.head=node;
            this.last=node;
        }else {
            node.next = this.head;
            this.head.prev = node;
            this.head = node;
        }
    }

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


    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index, int data) {
        if (index<0||index>size()){
            throw new RuntimeException("index不合法");
        }
        if (index==0){
            addFirst(data);
            return;
        }
        if (index==size()){
            addLast(data);
            return;
        }
        ListNode cur=findIndex(index);
        ListNode node=new ListNode(data);
        node.next=cur;
        node.prev=cur.prev;
        cur.prev.next=node;
        cur.prev=node;
    }

    private ListNode findIndex(int index){
        ListNode cur=this.head;
        while (index!=0){
            cur=cur.next;
            index--;
        }
        return cur;
    }

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

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

    //删除所有值为key的节点
    public void removeAllKey(int key) {
        ListNode cur=this.head;
        while (cur!=null){
            if (cur.val==key){
                if (cur==this.head){
                    this.head=this.head.next;
                    if (this.head!=null){
                        this.head.prev=null;
                    }
                }else {
                    cur.prev.next=cur.next;
                    if (cur!=null){
                        cur.next.prev=cur.prev;
                    }else {
                        this.last=this.last.prev;
                    }
                }
            }
            cur=cur.next;
        }
    }

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

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

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

四、ArrayList和LinkedList的区别

不同点

ArrayList

LinkedList

存储空间上

物理上一定连续

逻辑上连续,但物理上不一定连续

随机访问

支持O(1)

不支持:O(N)

头插

需要搬移元素,效率低O(N)

只需修改引用的指向,时间复杂度为O(1)

插入

空间不够时需要扩容

没有容量的概念

应用场景

元素高效存储+频繁访问

任意位置插入和删除频繁

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值