深入理解LinkedList

1,认识LinkedList

LinkedList是基于双链表实现的,具有双链表特性

LinkedList内部封装的是双向链表数据结构,每个节点是一个Node对象。
Node对象中封装的是要被添加的元素,还有一个指向上一个Node对象的引用和 指向下一个Node对象的引用 , 与ArrayList容器相比,不同的容器有不同的数据结构,不同的数据结构操作起来性能不同。
链表数据结构,做插入删除的效率比较高,但查询效率比较低 。 而数组结构(线性)做查询时效率高,可以直接通过下标来直接找到元素,但插入和删除效率低, 插入或删除元素后数组其他元素要做移位操作, 当需要频繁进行增删操作,使用LinkedList效率高,当只需要查询功能时,使用ArrayList容器效率高

2,类图关系

在这里插入图片描述

3,走进源码

  • 数据结构
//连表长度
transient int size = 0;
//头结点指针
transient Node<E> first;
//尾结点指针
transient Node<E> last;

Node数据结构,node是一个内部私有静态类

 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.1,构造函数

  • 空构造函数
  public LinkedList() {
    }
  • 根据一个集合来创建一个带有指定元素的列表
 public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

3.2添加元素

  • 添加元素到头结点
public void addFirst(E e) {
        linkFirst(e);
    }

linkFirst()方法

private void linkFirst(E e) {
		//获取头结点
        final Node<E> f = first;
        //创建一个新的节点
        //因为该节点是头结点,所有构造函数一个指针为null,
        //将节点newNode 的后置节点指向原头结点f,连接起来
        final Node<E> newNode = new Node<>(null, e, f);
        //更新头结点
        first = newNode;
        //f==null是空链表的情况下,添加了一个元素时,链表的头指针也是尾指针
        if (f == null)
            last = newNode;
        else
        //双链表结构的特性,所以有以下连接
        //原头结点的前置节点指向新的节点,newNode成为新的头结点
            f.prev = newNode;
        size++;
        modCount++;
    }
  • 添加元素到尾结点
 public void addLast(E e) {
        linkLast(e);
    }

linikLast()方法,(与linkFirst()方法的相反操作)

 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++;
    }
  • 将指定的元素追加到此列表的末尾
public boolean add(E e) {
        linkLast(e);
        return true;
    }
  • 将指定集合中的所有元素附加到此列表的末尾,以指定集合的​​迭代器返回它们的顺序

如果在操作正在进行中修改了指定的集合,则该操作的行为是不确定的。 (请注意,如果指定的集合是此列表,并且是非空的,则将发生这种情况。)

 public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

addAll()方法,从LinkedList的指定位置开始,附加指定集合中的所有元素到链表里。

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;
            //newNode的前置节点指向pred节点
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
            	//原末端链表节点的后置节点指向新创建的newNode节点
                pred.next = newNode;
            //更新前置节点
            pred = newNode;
        }
		//默认从链表的末端开始附加,会出现succ=null的情况
        if (succ == null) {
        	//更新末端指针指向
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

流程草图,大概这个样子
在这里插入图片描述

checkPositionIndex(index) 方法
指定位置超出连表长度,则会抛出异常

 private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

isPositionIndex(index)方法
判断指定位置是否超出连表长度

  private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

3.3删除元素

  • 删除头结点
 public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

unlinkFirst(f)方法

   private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        //获取元素值
        final E element = f.item;
        //获取f的后置节点
        final Node<E> next = f.next;
        //f节点元素置空,后置指针置空
        f.item = null;
        f.next = null; // help GC
        //更新连表头结点
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
  • removeLast()删除尾结点
    跟removeFirst()极为相似
  • 从此列表中删除第一次出现的指定元素,如果存在的话。
 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;
    }

unlink(x)方法

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;
    }
  • 删除此列表中指定位置的元素
  public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

3.4更改元素

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

3.5.查询

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linked List 是一种常见的数据结构,它由一组节点组成,每个节点包含一个值和一个指向下一个节点的指针。在 C++ STL 中,LinkedList 的实现是通过双向链表(doubly linked list)来完成的。下面是部分 LinkedList 的源码分析。 ```cpp template <class T> class list { protected: struct list_node { list_node* prev; list_node* next; T data; }; ... }; ``` 在这段代码中,`list_node` 是双向链表的节点类型,包含了 `prev` 和 `next` 两个指针,以及存储的数据 `data`。 ```cpp template <typename T, typename Alloc = allocator<T> > class _List_base { public: typedef Alloc allocator_type; allocator_type get_allocator() const noexcept { return allocator_type(); } struct _Node { _Node* _M_next; _Node* _M_prev; T _M_data; }; ... }; ``` `_List_base` 作为 LinkedList 的底层实现,定义了节点类型 `_Node`,包含了 `_M_next` 和 `_M_prev` 两个指针,以及存储的数据 `_M_data`。此外,还提供了 `get_allocator()` 方法,用于获取当前 LinkedList 使用的内存分配器。 ```cpp template <typename T, typename Alloc = allocator<T> > class list : protected _List_base<T, Alloc> { protected: typedef _List_base<T, Alloc> _Base; typedef typename _Base::_Node _Node; public: typedef typename _Base::allocator_type allocator_type; ... }; ``` `list` 类继承自 `_List_base`,并且定义了一些类型别名,例如 `allocator_type`,用于表明当前 LinkedList 使用的内存分配器类型。 ```cpp template <typename T, typename Alloc = allocator<T> > class list { public: ... class iterator { public: typedef bidirectional_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; ... }; ... }; ``` 在 LinkedList 中,迭代器(iterator)被广泛使用。在 C++ STL 中,迭代器的定义是一个 class,包含了一些成员类型,例如 `iterator_category`、`value_type`、`difference_type`、`pointer` 和 `reference` 等。这些成员类型用于描述当前迭代器的特征,例如 `iterator_category` 描述了迭代器的类别。 以上只是 LinkedList 的源码的一部分,LinkedList 的实现非常复杂,涉及到很多内存管理、迭代器、算法等内容。如果想要深入理解 LinkedList 的实现,需要读者具备一定的 C++ 知识和数据结构基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值