• List集合-02.LinkedList


    2.LinkedList

    2.1 UML继承关系图

    2.2 底层存储节点

    • 通过内部类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;
            }
        }
    
    
    • add方法是在最后一个node节点增加关联
      可以看出LinkedList是开链表,首尾不相连,不会形成闭环
    transient Node<E> last;
     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++;
        }
    
    • get,remove方法
      对list长度除以2,判断是前部分还是后部分,再进行,循环取值;
     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;
            }
        }
    
    

    2.3 ListIterator迭代器

    • 可以指定开始迭代位置
     ListItr(int index) {
                // assert isPositionIndex(index);
                next = (index == size) ? null : node(index);
                nextIndex = index;
            }
    
    
    • remove,set方法前必须要用next()方法,将当前节点缓存到lastReturned
    private Node<E> lastReturned;//用于存储切换的node节点
    
    • add 方法根据节点位置,进行判断在节点之前增加,还是节点之后增加
     lastReturned = null;
      if (next == null)
          linkLast(e);
      else
          linkBefore(e, next);
    

    2.3 常用增删方法实现

    • poll,poll,removeFirst 方法,从头部取出数据,并从list中移除该节点
     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;
        }
    

    -push 方法是从头部增加节点数据

    2.4 LinkedList 内部提供了切分的方法

     LLSpliterator<E> implements Spliterator<E> 
    

    总结一下:
    1.LinkedList的存储时通过Node对象存储的,Node对象有pre,next双向链关联前后Node;FirstNode的pre为空,LastNode的next为空,不能形成闭合的链表;
    2.迭代器在移除Node之前,必须使用node方法,缓存当前节点信息否则会报错;
    3.LinkedList提供了pop,pull等方法,从头部获取并移除Node

  • 相关阅读:
    js常用方法收集
    Jquery的常用使用方法
    jQuery css()选择器使用说明
    解决IE6,边框问题
    HTML问题集锦及笔记
    我的第一个chrome扩展(3)——继续读样例
    我的第一个chrome扩展(0)——目标
    我的第一个chrome扩展(2)——基本知识
    我的第一个chrome扩展(1)——读样例,实现时钟
    2の奇妙用法
  • 原文地址:https://www.cnblogs.com/perferect/p/12955549.html
Copyright © 2020-2023  润新知