【Java基础】Java集合(3)--LinkedList

108 阅读5分钟

他的灵魂时常能跃出残疾的身体,奔向更远的地方,有时候甚至可以飞起来,俯视他爱的世界,他爱的人。没有一句是向命运挑战那样激昂的宣言,但每一句又都是对命运抗争,他用笔铸造了完美的灵魂。—— 宜梦想

LinkedList概述

介绍

  1. LinkedList底层数据结构是双向链表
  2. Linkedlist实现了List接口和Deque接口,可以作为顺序容器,队列和栈使用。但是如果需要使用栈或者队列,首选ArrayDeque,比LinkedList有更好的性能。
  3. LinkedList对首尾数据进行操作时间复杂度为O(1),其他位置的时间复杂度为O(n)。 LinkedList0.png

基本操作

LinkedList.png

源码

属性和内部类

属性

transient int size = 0;

/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) ||
 *            (first.prev == null && first.item != null)
 */
transient Node<E> first;

/**
 * Pointer to last node.
 * Invariant: (first == null && last == null) ||
 *            (last.next == null && last.item != null)
 */
transient Node<E> last;

内部类:item:存储对象;next:指向后一个节点;prev:指向前一个节点。

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

构造函数

//空链表
public LinkedList() {
}
//传入一个集合类型作为参数,创建一个和传入的集合类型相同的链表对象
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

获取操作

  • getFirst() :获取第一个元素
  • getLast() :获取最后一个元素
  • get() :获取指定位置元素
public E getFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return f.item;
}

public E getLast() {
    final Node<E> l = last;
    if (l == null)
        throw new NoSuchElementException();
    return l.item;
}

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}
                                                                                               

插入操作

  • add(E e);addLast(E e) :在尾部插入一个元素
  • add(int index, E element) :在指定位置插入一个元素
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));
}

// 将元素插入到链表末尾
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}
//将元素插入到指定位置之前
void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    final Node<E> pred = succ.prev;
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}
//寻找指定位置的元素
Node<E> node(int index) {
    // 靠近首部,从首部开始寻找
    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else { //靠近尾部,从末尾开始寻找
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}
  • addAll(Collection<? extends E> c) :在链表末尾添加多个元素,直接调用下面方法,令index=size
  • addAll(int index, Collection<? extends E> c) : 在链表指定位置添加多个元素
public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}

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

    // 将集合c转换为Object数组,如果为空则直接返回
    Object[] a = c.toArray();
    int numNew = a.length;
    if (numNew == 0)
        return false;

    //定义节点pred和succ,并根据插入位置是否为末尾进行赋值
    Node<E> pred, succ;
    if (index == size) {
        succ = null;
        pred = last;
    } else {
        succ = node(index);
        pred = succ.prev;
    }

    //遍历数组进行插入
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        //用数组中的每个元素创建新的节点
        Node<E> newNode = new Node<>(pred, e, null);
        //判断插入位置是否为开端进行插入
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        pred = newNode;
    }
    //插入之后是否还有元素
    if (succ == null) {
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }
    
    size += numNew;
    modCount++;
    return true;
}

删除操作

  • remove(Object o) :删除第一个出现的指定元素
  • remove(int index) :删除指定位置的元素
  • removeFirst() : 删除链表第一个元素
  • removeLast() : 删除链表最后一个元素
  • clear() : 清空所有元素
public boolean remove(Object o) {
    // 对链表进行遍历,是null或者第一个相等的元素都会调用unlink()方法删除该元素,成功返回true
    if (o == 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;
            }
        }
    }
    //不存在该元素直接返回false
    return false;
}

//通过node方法找到该位置的元素,然后调用unlink()方法
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}

E unlink(Node<E> x) {
    // assert x != null;
    //暂存元素的数据,前驱和后继
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    //前驱为空,则是第一个节点,first直接指向下一个元素,即去除引用
    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    //后继为空,则是最后一个节点,last直接指向前驱,即去除引用
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    //元素数据赋值为null,长度减一,最后返回已经删除的元素的数据
    x.item = null;
    size--;
    modCount++;
    return element;
}

public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

private E unlinkFirst(Node<E> f) {
    // assert f == first && f != null;
    final E element = f.item;
    final Node<E> next = f.next;
    f.item = null;
    f.next = null; // help GC
    first = next;
    if (next == null)
        last = null;
    else
        next.prev = null;
    size--;
    modCount++;
    return element;
}

public E removeLast() {
    final Node<E> l = last;
    if (l == null)
        throw new NoSuchElementException();
    return unlinkLast(l);
}

private E unlinkLast(Node<E> l) {
    // assert l == last && l != null;
    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;
}

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(Object o) : 查找第一个指定元素的位置
  • lastIndexOf(Object o) : 查找最后一个指定元素的位置
//indexof()从前向后找,lastIndexOf()从后向前找
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++;
        }
    }
    // 没有指定元素则返回-1
    return -1;
}

public int lastIndexOf(Object o) {
    int index = size;
    if (o == null) {
        for (Node<E> x = last; x != null; x = x.prev) {
            index--;
            if (x.item == null)
                return index;
        }
    } else {
        for (Node<E> x = last; x != null; x = x.prev) {
            index--;
            if (o.equals(x.item))
                return index;
        }
    }
    //没有指定元素返回-1
    return -1;
}

其他

继承自Queue,Deque接口的方法具体实现几乎都是调用上面的方法完成的。

参考

Java LinkedList源码剖析 - CarpenterLee - 博客园 (cnblogs.com)
LinkedList 源码分析 | JavaGuide(Java面试 + 学习指南)
Collection - LinkedList源码解析 | Java 全栈知识体系 (pdai.tech)