欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK源码系列:LinkedList

程序员文章站 2022-04-19 18:24:35
...

简介

LinkedList是一个双向链表,实现了List和Deque接口。这意味着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;
        }
    }

addFirst

双向链表常规操作:

	public void addFirst(E e) {
    	linkFirst(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++;
    }

removeFirst

也是常规操作:

    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;
    }
相关标签: JDK源码