LinkedList源码分析及高频面试问题答案

本文详细剖析了LinkedList的内部实现,包括其双向链表结构、主要成员变量及方法,如构造、增删改查操作。探讨了LinkedList相较于ArrayList在增删操作上的优势及下标查找的劣势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看下继承结构

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

继承自AbstractSequentialList,并实现了List,Deque等接口。

主要成员变量:

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

可以看到成员很简单,首节点,尾节点,队列大小三个值。
Node 也很简单,元素本身,前一个元素指针,后一个元素指针,三个成员。

主要方法:
首先看构造方法

public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

有两种,一种是直接new一个空的LinkedList,一种是通过传入集合对象。
我们看下传入集合对象的具体操作:

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

将集合对象转化为数组,进行遍历添加至尾节点。该方法也可以在一个Linkedlist对象直接添加一个集合对象,如ArrayList或Set;

增,add方法

public boolean add(E e) {
    linkLast(e);
    return true;
}
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++;
}

根据传入参数生成node元素并添加到队尾。

指定位置增加元素add(int index, E element)方法

 public void add(int index, E element) {
    checkPositionIndex(index);

    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}
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++;
}

将该地点的前元素的后项指针指向自己,并将该地点的元素的前指针指向自己,于是自己就成功的加入链表的指定位置了。

删:指定位置删除元素remove(int index)

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;

    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

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

将该node的前后指针指向null,将其前元素的后指针指向自己的后元素,将该node的后元素的前指针指向自己的前元素。

来看一个重要的方法:node(index)

Node<E> node(int index) {
    // assert isElementIndex(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;
     }
 }

可以看到是将列表分为两半,根据index所在的位置,可以从前或后查找,从而最多增加一倍的查询效率。这也是为什么LinkedList使用双向链表的优势。

删:指定元素删除remove(Object o)

public boolean remove(Object o) {
    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;
            }
        }
    }
    return false;
}

可以看到是通过遍历,寻找第一个元素,删除。

删:清空所有元素clear()

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

遍历每个节点,将元素本身,前后指针都置为null。

改:set(int index, E element)

 public E set(int index, E element) {
   checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

将元素改为新值,并返回旧值。

查:根据index get(int index)

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

可以看到还是根据node方法,前后遍历找到的,所以根据下标查找效率较低,时间复杂度跟index位置和列表长度有关,最差为O(n/2)

查:是否包含contains(Object o)

public boolean contains(Object o) {
    return indexOf(o) != -1;
}
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;
}

可以看到是遍历查找,跟ArrayList一样。

面试中经常问到的相关问题:

LinkedList为什么使用双向链表?
双向链表可以根据下标查找元素即Node(index),可以通过前后两个方向查找,是查找效率提高一倍。见上面源码分析。

LinkedList的优缺点是什么?
优点:可以方便的增删任何节点的数据,不需要大量复制数据,只该前后几个指针效率较高(跟ArrayList相比),不需要预先指定数据长度避免空节点浪费和预留的长度不足等问题(跟数组相比)。
缺点:根据下标查找/删除/修改元素,都要通过遍历,效率较低。每个Node保留了除元素本身外前后两个指针,空间有所浪费。(与ArrayList相比)

LinkedList使用场景有哪些?
适用于不需要根据下标查询的可变长列表的情况。在需要对元素大量增删情况下使用相比ArrayList要高效很多

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值