数据结构List之LinkedList

LinkedList

存储方式 双向链表存储方式

优点:插入、删除效率高

缺点:遍历、查询较慢

结构

    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;

添加

add() 是 尾插

public boolean add(E e) {
        linkLast(e);
        return true;
    }
    
public void addLast(E e) {
    linkLast(e);
}

查询

get(int index)
分别从头或尾部开始遍历

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    
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;
    }
}

猜你喜欢

转载自blog.csdn.net/u012768625/article/details/107763192
今日推荐