LinkedList源码分析

本文深入剖析了Java中LinkedList的实现原理,包括其内部结构、核心方法及双端队列功能,适合希望深入了解数据结构及Java集合框架的读者。

本文源代码版本为1.7

LinkedList:以双向链表实现。链表无容量限制,但双向链表本身使用了更多空间,也需要额外的链表指针操作。
注意:构建的链表不带头节点。

链表的节点代码:

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类头:

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

可以看出LinkedList 继承AbstractSequentialList 抽象类,实现了List,Deque,Cloneable,Serializable 几个接口。
其中,AbstractSequentialList 继承 AbstractList,是对其中方法的再抽象,其主要作用是最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作,简单说就是,如果需要快速的添加删除数据等,用AbstractSequentialList抽象类,若是需要快速随机的访问数据等用AbstractList抽象类。
实现了Deque接口,即代表着LinkedList可以实现队列的功能。

属性:

//链表的长度
transient int size = 0;
//指向链表头
transient Node<E> first;
//指向链表尾
transient Node<E> last;
private static final long serialVersionUID = 876323262645176354L;

构造函数:

//空构造方法
public LinkedList() {
}

//将集合转换成链表
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

链表底层操作方法:


//私有函数,用户调用不了,删除链表的第一个节点(即f,f必须等于first,且不能为空),返回删除节点的值
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;
    if (next == null)
        last = null;
    else
        next.prev = null;
    size--;
    modCount++;
    return element;
}

//私有函数,用户调用不了,删除链表的最后一个节点,(即l,l == last && l != null),返回删除节点的值
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;
}

//删除链表中的节点x,x != null
E unlink(Node<E> x) {
    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;
}
  • 添加链表元素的函数:
//在链表头部节点前,插入元素e
private void linkFirst(E e) {
    final Node<E> f = first;
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    if (f == null)
        last = newNode;
    else
        f.prev = newNode;
    size++;
    modCount++;
}

//在链表尾部节点后,插入元素e的节点
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++;
}

//在链表中节点succ(必须是非null)的前面插入元素是e的节点
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++;
}

//在链表头部节点前,添加节点e
public void addFirst(E e) {
    linkFirst(e);
}

//在链表尾部节点后,添加节点e
public void addLast(E e) {
    linkLast(e);
}

//在链表尾部节点后,添加节点e
public boolean add(E e) {
   linkLast(e);
   return true;
}

//将集合c中的所有元素,按集合中的顺序,生成节点,添加到链表的尾部
public boolean addAll(Collection<? extends E> c) {
   return addAll(size, c);
}

//将集合c中的所有元素,按集合中的顺序,生成节点,添加到链表中index位置的节点前,若index==size,则添加到节点尾部。
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;
}

//在当前链表index位置的节点前,添加元素值为element的节点,若index==size,则在链表尾部添加。
public void add(int index, E element) {
   checkPositionIndex(index);

    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}
  • 查找链表中节点的函数:
//查找index位置的节点,并返回该节点,此函数不对传入的位置进行安全性检查,而且当index小于当前链表长度的一般时,从前向后查找,大于时,从后向前查找,提高了效率。
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;
    }
}

//在当前链表中,从前向后查找第一个元素值为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;
}

//在当前链表中,从前向后查找第一个元素值为o的节点位置,找不到返回-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;
        }
    }
    return -1;
}
  • 获取链表中节点的元素值函数:
//获取链表的第一个节点元素值
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;
}

//获取链表中index位置的节点的元素值
public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}
  • 删除链表中节点的函数:
//删除链表中第一个节点,返回其元素值。
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);
}

//删除链表中元素值为o的节点,注意其调用了o的equals()进行元素的比较,若没有改写o的equals(),可能会出错。
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;
}

//清除链表中的所用节点
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++;
}

//删除链表中index位置的节点,返回其元素值。
public E remove(int index) {
   checkElementIndex(index);
    return unlink(node(index));
}

//删除链表中第一个元素值为o的节点,从前向后找
public boolean removeFirstOccurrence(Object o) {
    return remove(o);
}

//删除链表中第一个元素值为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;
}
  • 其他函数:
public boolean contains(Object o)
public E set(int index, E element)
private void writeObject(java.io.ObjectOutputStream s)
private void readObject(java.io.ObjectInputStream s)
  • LinkedList实现的Deque双端队列的方法:
注意:可以用这些方法实现队列和栈
public E peek()
public E element()
public E poll()
public E remove()
public boolean offer(E e)
public boolean offerFirst(E e)
public boolean offerLast(E e)
public E peekFirst()
public E peekLast()
public E pollFirst()
public E pollLast()
public void push(E e)
public E pop()
  • 几个重要函数:
克隆:就是一个浅拷贝(只是拷贝了引用)
private LinkedList<E> superClone() {
   try {
        return (LinkedList<E>) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new InternalError();
    }
}

public Object clone() {
   LinkedList<E> clone = superClone();

    // Put clone into "virgin" state
    clone.first = clone.last = null;
    clone.size = 0;
    clone.modCount = 0;

    // Initialize clone with our elements
    for (Node<E> x = first; x != null; x = x.next)
        clone.add(x.item);

    return clone;
}
迭代器:实现类前后都可以遍历的迭代器类
public ListIterator<E> listIterator(int index) {
   checkPositionIndex(index);
    return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
    private Node<E> lastReturned = null;
    private Node<E> next;
    private int nextIndex;
    private int expectedModCount = modCount;

    ListItr(int index) {
        // assert isPositionIndex(index);
        next = (index == size) ? null : node(index);
        nextIndex = index;
    }

    public boolean hasNext() {
        return nextIndex < size;
    }

    public E next() {
        checkForComodification();
        if (!hasNext())
            throw new NoSuchElementException();

        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }

    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    public E previous() {
        checkForComodification();
        if (!hasPrevious())
            throw new NoSuchElementException();

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

    public int nextIndex() {
        return nextIndex;
    }

    public int previousIndex() {
        return nextIndex - 1;
    }

    public void remove() {
        checkForComodification();
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }

    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();
        lastReturned.item = e;
    }

    public void add(E e) {
        checkForComodification();
        lastReturned = null;
        if (next == null)
            linkLast(e);
        else
            linkBefore(e, next);
        nextIndex++;
        expectedModCount++;
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
//降序迭代器类,从末尾向头节点遍历的迭代器类
public Iterator<E> descendingIterator() {
    return new 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();
    }
}
【博士论文复现】【阻抗建模、验证扫频法】光伏并网逆变器扫频与稳定性分析(包含锁相环电流环)(Simulink仿真实现)内容概要:本文档围绕“博士论文复现”主题,重点介绍了光伏并网逆变器的阻抗建模与扫频法稳定性分析,涵盖锁相环和电流环的Simulink仿真实现。文档旨在通过完整的仿真资源和代码帮助科研人员复现相关技术细节,提升对新能源并网系统动态特性和稳定机制的理解。此外,文档还提供了大量其他科研方向的复现资源,包括微电网优化、机器学习、路径规划、信号处理、电力系统分析等,配套MATLAB/Simulink代码与模型,服务于多领域科研需求。; 适合人群:具备一定电力电子、自动控制或新能源背景的研究生、博士生及科研人员,熟悉MATLAB/Simulink环境,有志于复现高水平论文成果并开展创新研究。; 使用场景及目标:①复现光伏并网逆变器的阻抗建模与扫频分析过程,掌握其稳定性判据与仿真方法;②借鉴提供的丰富案例资源,支撑博士论文或期刊论文的仿真实验部分;③结合团队提供的算法与模型,快速搭建实验平台,提升科研效率。; 阅读建议:建议按文档目录顺序浏览,优先下载并运行配套仿真文件,结合理论学习与代码调试加深理解;重点关注锁相环与电流环的建模细节,同时可拓展学习其他复现案例以拓宽研究视野。
LinkedList是Java中提供的一个双向链表实现类,其内部维护了一个first和last节点,分别表示链表的头和尾。以下是LinkedList源码分析: 1. 声明LinkedList类 ```java public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { transient int size = 0; transient Node<E> first; transient Node<E> last; } ``` 2. 声明Node类 ```java 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; } } ``` 3. 实现LinkedList的方法 - add(E e)方法:将元素添加到链表末尾 ```java 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++; } ``` - add(int index, E element)方法:将元素插入到指定位置 ```java 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) { 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++; } ``` - remove(int index)方法:删除指定位置的元素 ```java public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } E unlink(Node<E> x) { 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--; return element; } ``` - get(int index)方法:获取指定位置的元素 ```java public E get(int index) { checkElementIndex(index); return node(index).item; } 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; } } ``` 以上就是LinkedList源码分析,通过对其源码的分析,我们可以更深入地理解链表的实现。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值