Java 集合深入理解:LinkedList

LinkedList这个类需要仔细看一下,因为平时用的不多,了解熟悉后,在指定场景,可以活学活用,丰富一下自己;

我们知道 ArrayList 是以数组实现的,遍历时很快,但是插入、删除时都需要移动后面的元素,效率略差些。

而LinkedList 是以链表实现的,插入、删除时只需要改变前后两个节点指针指向即可。

今天来看下 LinkedList 源码。

源码

LinkedList继承结构

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{}

LinkedList 继承自 AbstractSequentialList 接口,同时了还实现了 Deque, Queue 接口。

LinkedList 双向链表实现

    transient int size = 0;
    
    transient Node<E> first;
    
    transient Node<E> last;
    
    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

可以看到, LinkedList 的成员变量只有三个

  • size容量
  • first头节点
  • last尾节点

节点包含两个节点和一个存放数据的成员,其中prev指向上一个节点,next指向下一个节点,item用于存放数据;
在这里插入图片描述

LinkedList 的方法

1.关键的几个内部方法(头部添加删除,尾部添加删除,获取指定节点,指定节点的添加删除)

//插入到头部
private void linkFirst(E e) {
    //获取头节点
    final Node<E> f = first;
    //新建一个节点,尾部指向之前的 头元素 first
    final Node<E> newNode = new Node<>(null, e, f);
    //first 指向新建的节点
    first = newNode;
    //如果之前是空链表,新建的节点 也是最后一个节点
    if (f == null)
        last = newNode;
    else
        //原来的第一个节点(现在的第二个)头部指向新建的头结点
        f.prev = newNode;
    size++;
    modCount++;
}

//插入到尾部
void linkLast(E e) {
    //获取尾部节点
    final Node<E> l = last;
    //新建一个节点,头部指向之前的 尾节点 last
    final Node<E> newNode = new Node<>(l, e, null);
    //last 指向新建的节点
    last = newNode;
    //如果之前是空链表, 新建的节点也是第一个节点
    if (l == null)
        first = newNode;
    else
        //原来的尾节点尾部指向新建的尾节点
        l.next = newNode;
    size++;
    modCount++;
}

//在 指定节点 前插入一个元素,这里假设 指定节点不为 null
void linkBefore(E e, Node<E> succ) {
    // 获取指定节点 succ 前面的一个节点
    final Node<E> pred = succ.prev;
    //新建一个节点,头部指向 succ 前面的节点,尾部指向 succ 节点,数据为 e
    final Node<E> newNode = new Node<>(pred, e, succ);
    //让 succ 节点头部指向 新建的节点
    succ.prev = newNode;
    //如果 succ 前面的节点为空,说明 succ 就是第一个节点,那现在新建的节点就变成第一个节点了
    if (pred == null)
        first = newNode;
    else
        //如果前面有节点,让前面的节点
        pred.next = newNode;
    size++;
    modCount++;
}

//删除头节点并返回该节点上的数据,假设不为 null
private E unlinkFirst(Node<E> f) {
    // 获取数据,一会儿返回
    final E element = f.item;
    //获取头节点后面一个节点
    final Node<E> next = f.next;
    //使头节点上数据为空,尾部指向空
    f.item = null;
    f.next = null; // help GC
    //现在头节点后边的节点变成第一个了
    first = next;
    //如果头节点后面的节点为 null,说明移除这个节点后,链表里没节点了
    if (next == null)
        last = null;
    else
        next.prev = null;
    size--;
    modCount++;
    return element;
}

//删除尾部节点并返回,假设不为空
private E unlinkLast(Node<E> l) {

    final E element = l.item;
    //获取倒数第二个节点
    final Node<E> prev = l.prev;
    //尾节点数据、尾指针置为空
    l.item = null;
    l.prev = null; // help GC
    //现在倒数第二变成倒数第一了
    last = prev;
    if (prev == null)
        first = null;
    else
        prev.next = null;
    size--;
    modCount++;
    return element;
}

//删除某个指定节点
E unlink(Node<E> x) {
    // 假设 x 不为空
    final E element = x.item;
    //获取指定节点前面、后面的节点
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    //如果前面没有节点,说明 x 是第一个
    if (prev == null) {
        first = next;
    } else {
        //前面有节点,让前面节点跨过 x 直接指向 x 后面的节点
        prev.next = next;
        x.prev = null;
    }

    //如果后面没有节点,说 x 是最后一个节点
    if (next == null) {
        last = prev;
    } else {
        //后面有节点,让后面的节点指向 x 前面的
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}

//获取指定位置的节点
Node<E> node(int index) {
    // 假设指定位置有元素

    //二分一下,如果小于 size 的一半,从头开始遍历
    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        //大于 size 一半,从尾部倒着遍历
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

总结一下,这些内部方法实现了对 链表节点的 基本修改操作,每次操作都只要修改前后节点的指针,时间复杂度为 O(1)。

公开添加方法

//在尾部添加元素
public boolean add(E e) {
    linkLast(e);
    return true;
}

//在指定位置添加元素
public void add(int index, E element) {
    checkPositionIndex(index);
    //指定位置也有可能是在尾部
    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}

//添加一个集合的元素
public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);

    //把 要添加的集合转成一个 数组
    Object[] a = c.toArray();
    int numNew = a.length;
    if (numNew == 0)
        return false;

    //创建两个节点,分别指向要插入位置前面和后面的节点
    Node<E> pred, succ;
    //要添加到尾部
    if (index == size) {
        succ = null;
        pred = last;
    } else {
        //要添加到中间, succ 指向 index 位置的节点,pred 指向它前一个
        succ = node(index);
        pred = succ.prev;
    }

    //遍历要添加内容的数组
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        //创建新节点,头指针指向 pred
        Node<E> newNode = new Node<>(pred, e, null);
        //如果 pred 为空,说明新建的这个是头节点
        if (pred == null)
            first = newNode;
        else
            //pred 指向新建的节点
            pred.next = newNode;
        //pred 后移一位
        pred = newNode;
    }

    //添加完后需要修改尾指针 last
    if (succ == null) {
        //如果 succ 为空,说明要插入的位置就是尾部,现在 pred 已经到最后了
        last = pred;
    } else {
        //否则 pred 指向后面的元素
        pred.next = succ;
        succ.prev = pred;
    }

    //元素个数增加
    size += numNew;
    modCount++;
    return true;
}

//添加到头部,时间复杂度为 O(1)
public void addFirst(E e) {
    linkFirst(e);
}

//添加到尾部,时间复杂度为 O(1)
public void addLast(E e) {
    linkLast(e);
}

继承自双端队列的添加方法由于未看过代码,所以先不做为学习点

公开删除和修改方法

//删除头部节点
public E remove() {
    return removeFirst();
}

//删除指定位置节点
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}

//删除包含指定元素的节点,这就得遍历了
public boolean remove(Object o) {
    if (o == null) {
        //遍历终止条件,不等于 null
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

//删除头部元素
public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

//删除尾部元素
public E removeLast() {
    final Node<E> l = last;
    if (l == null)
        throw new NoSuchElementException();
    return unlinkLast(l);
}

//删除首次出现的指定元素,从头遍历
public boolean removeFirstOccurrence(Object o) {
    return remove(o);
}

//删除最后一次出现的指定元素,倒过来遍历
public boolean removeLastOccurrence(Object o) {
    if (o == null) {
        for (Node<E> x = last; x != null; x = x.prev) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = last; x != null; x = x.prev) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

//set 很简单,找到这个节点,替换数据就好了
public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

清除全部元素其实只需要把首尾都置为 null, 这个链表就已经是空的,因为无法访问元素。
但是为了避免浪费空间,需要遍历把中间节点都置为 null:

public void clear() {
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

公开的查询方法(以indexOf为例)

//遍历,获取第一次出现位置
public int indexOf(Object o) {
    int index = 0;
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null)
                return index;
            index++;
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item))
                return index;
            index++;
        }
    }
    return -1;
}

DescendingIterator 倒序迭代器

    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }
    
        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

总结

LinkedList 特点
  • 双向链表实现
  • 和 ArrayList 一样,不是同步容器

其他比如

  • 元素时有序的,输出顺序与输入顺序一致
  • 允许元素为 null
  • 所有指定位置的操作都是从头开始遍历进行的
解决并发访问的问题

linkedList 和 ArrayList 一样,不是同步容器。所以需要外部做同步操作,或者直接用 Collections.synchronizedList 方法

List list = Collections.synchronizedList(new LinkedList(...));
下面是面试中会问到的一个问题

ArrayList 和 LinkedList区别:

  • ArrayList 底层实现是数组,而LinkedList是双向链表
  • ArrayList 由于是根据索引搜索,搜索和读取数据是很快的。因此 ArrayList 获取数据的时间复杂度是O(1);
    而LinkedList只能顺序遍历,无法按照索引获得元素,因此查询效率不高;
  • ArrayList 添加、删除时该元素后面的所有元素都要移动,所以添加/删除数据效率不高;
    而LinkedList添加/删除元素只需要修改周围的两个节点;
  • ArrayList 有容量,到达容量后需要重新申请一个数组将数据复制过去进行扩容,这个操作比较影响效率;
    而LinkedList没有固定容量,不需要扩容
  • LinkedList底层是双向链表,因此需要比ArrayList 多维护两个节点,占用空间更多些。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值