一个学生对Linkedlist源码分析注释

public class LinkedList<E>
    extends AbstractSequentialList<E>//其实AbstractSequentialList已经实现了list接口只是这里的list有更加清晰的作用
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable//Deque定义了双端队列的操作
{
    private transient Entry<E> header = new Entry<E>(null, null, null);//头结点,上一个索引和下一个索引都指向空,说明是可以循环遍历的
    private transient int size = 0;//链表里面的节点个数

    /**
     * 构造方法1:构造一个空链表
     */
    public LinkedList() {
        header.next = header.previous = header;//指向自己
    }

    /**
     * 构造方法2:构造一个链表,参数为一个集合Collection,并调用第一个构造方法构造一个空链表,并使用addAll()方法将c全部放进去
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

//最后一个就是header的前一个
    public E getLast()  {
        if (size==0)
            throw new NoSuchElementException();

        return header.previous.element;
    }

    public boolean contains(Object o) {//调用了indexOf()方法,因为indexOf方法返回包含值得索引,返回-1就是没有
        return indexOf(o) != -1;
    }

    public boolean remove(Object o) {//删除方法,在这里会调用参数类型为Entry的remove方法
        if (o==null) {//分两种情况空和非空
            for (Entry<E> e = header.next; e != header; e = e.next) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            for (Entry<E> e = header.next; e != header; e = e.next) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 第二个构造函数被调用,他相应的调用addAll的另一个重构的有size参数的addAll方法
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     *index是第一个元素插入的位置,c为集合参数
     */
    public boolean addAll(int index, Collection<? extends E> c) {	

        if (index < 0 || index > size)//这是错误检查
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);//插入位置和数组大小异常
											
        Object[] a = c.toArray();//调用集合的toArray方法,集合的元素放进新创建的Object[]数组
        int numNew = a.length;//获取数组长度,也是元素个数
	
        if (numNew==0)//这是错误检查
            return false;
        modCount++;//这个更改链表的修改的次数	
		
        Entry<E> successor = (index==size ? header : entry(index));//标记当前要插入节点的后一个节点,要插入的位置就是的尺寸的话,就把头结点赋值给它,他跟header一样指向同一个节点
        Entry<E> predecessor = successor.previous;//当前要插入的节点的下一个节点,因为header.previous就是header,所以predecessor还是指向头结点
        for (int i=0; i<numNew; i++) {
            Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
            predecessor.next = e;//链表的正相连接
            predecessor = e;//讲predecessor移位,指向下次要插入的节点的上一个节点
        }
        successor.previous = predecessor;//最后的修补工作

        size += numNew;//修改链表尺寸
        return true;
    }

    public void clear() {//e指向当前需要清空的节点,从第一个开始,也就是header的后一个,当e为header时,说明已经清理完成。遍历清空方便gc
        Entry<E> e = header.next;
        while (e != header) {
            Entry<E> next = e.next;
            e.next = e.previous = null;//设置当前节点的上下索引为空
            e.element = null;//当前节点内容为空
            e = next;//跳至下一个
        }
        header.next = header.previous = header;//构造一个和无参构造方法一个只有头结点的空链表
        size = 0;//尺寸为零
        modCount++;
    }

    /**
     * 返回索引出的节点
     */
    private Entry<E> entry(int index) {
        if (index < 0 || index >= size)//错误检测
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;//折半查找,如果index在size前半段就从前面开始,否则反之,提高效率
        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else {
            for (int i = size; i > index; i--)
                e = e.previous;
        }
        return e;
    }

    public int indexOf(Object o) {//o为entry里面的值,查找o第一次出现的位置,所以index从0开始
        int index = 0;
        if (o==null) {
            for (Entry e = header.next; e != header; e = e.next) {
                if (e.element==null)
                    return index;
                index++;
            }
        } else {
            for (Entry e = header.next; e != header; e = e.next) {
                if (o.equals(e.element))
                    return index;
                index++;
            }
        }
        return -1;
    }

    public int lastIndexOf(Object o) {//查找o最后一次出现的位置,右后向前遍历,所以index从size开始
        int index = size;
        if (o==null) {
            for (Entry e = header.previous; e != header; e = e.previous) {
                index--;
                if (e.element==null)
                    return index;
            }
        } else {
            for (Entry e = header.previous; e != header; e = e.previous) {
                index--;
                if (o.equals(e.element))
                    return index;
            }
        }
        return -1;
    }

队列的操作:
    public E peek() {
        if (size==0)
            return null;
        return getFirst();
    }

    public E element() {
        return getFirst();
    }

    public E poll() {
        if (size==0)
            return null;
        return removeFirst();
    }

    public E remove() {
        return removeFirst();
    }

    public boolean offer(E e) {
        return add(e);
    }

双端队列操作:
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    public E peekFirst() {
        if (size==0)
            return null;
        return getFirst();
    }

    public E peekLast() {
        if (size==0)
            return null;
        return getLast();
    }

    public E pollFirst() {
        if (size==0)
            return null;
        return removeFirst();
    }

    public E pollLast() {
        if (size==0)
            return null;
        return removeLast();
    }

    public void push(E e) {
        addFirst(e);
    }

    public E pop() {
        return removeFirst();
    }

    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    public boolean removeLastOccurrence(Object o) {
        if (o==null) {
            for (Entry<E> e = header.previous; e != header; e = e.previous) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            for (Entry<E> e = header.previous; e != header; e = e.previous) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

迭代器:
    public ListIterator<E> listIterator(int index) {//获取一个ListItr
        return new ListItr(index);
    }

    private class ListItr implements ListIterator<E> {//这是一个类不是表示迭代器,参数index相当于构建一个指针,指向index的位置
	//当前的节点,也就是上次工作完后的越过的一个节点
        private Entry<E> lastReturned = header;
		//当前节点的下一个节点
        private Entry<E> next;
		//下一个节点的索引
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index) {
            if (index < 0 || index > size)
                throw new IndexOutOfBoundsException("Index: "+index+
               //把next指向index位置的节点                                     ", Size: "+size);
            if (index < (size >> 1)) {
                next = header.next;
                for (nextIndex=0; nextIndex<index; nextIndex++)
                    next = next.next;
            } else {
                next = header;
                for (nextIndex=size; nextIndex>index; nextIndex--)
                    next = next.previous;
            }
        }
//是都还有下一个
        public boolean hasNext() {
            return nextIndex != size;
        }
//获取下一个元素
        public E next() {
            checkForComodification();
            if (nextIndex == size)
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.element;
        }
//时候有上一个节点</span>
        public boolean hasPrevious() {
            return nextIndex != 0;
        }
//获取上一个元素
        public E previous() {
            if (nextIndex == 0)
                throw new NoSuchElementException();

            lastReturned = next = next.previous;
            nextIndex--;
            checkForComodification();
            return lastReturned.element;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex-1;
        }
// 删除双向链表中的当前节点</span>
        public void remove() {
            checkForComodification();
            Entry<E> lastNext = lastReturned.next;
            try {
                LinkedList.this.remove(lastReturned);
            } catch (NoSuchElementException e) {
                throw new IllegalStateException();
            }
            if (next==lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = header;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == header)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.element = e;
        }
// 将e添加到当前节点的前面</span>
        public void add(E e) {
            checkForComodification();
            lastReturned = header;
            addBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    private static class Entry<E> {
        E element;
        Entry<E> next;
        Entry<E> previous;

        Entry(E element, Entry<E> next, Entry<E> previous) {
            this.element = element;
            this.next = next;
            this.previous = previous;
        }
    }

    private Entry<E> addBefore(E e, Entry<E> entry) {//简单的在两个节点中插入并修改相应的指针,这是个私有的方法!
        Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
        newEntry.previous.next = newEntry;
        newEntry.next.previous = newEntry;
        size++;
        modCount++;
        return newEntry;
    }
//这是remove最底层的方法
    private E remove(Entry<E> e) {
        if (e == header)
            throw new NoSuchElementException();

        E result = e.element;
        e.previous.next = e.next;
        e.next.previous = e.previous;
        e.next = e.previous = null;
        e.element = null;
        size--;
        modCount++;
        return result;
    }
//反向迭代器
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }
//反向迭代器实现类
    private class DescendingIterator implements Iterator {
        final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    public Object clone() {//调用父类的clone()再然后创建一个空链表,然后在把节点逐个放进去
        LinkedList<E> clone = null;
        try {
            clone = (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }

        // Put clone into "virgin" state
        clone.header = new Entry<E>(null, null, null);
        clone.header.next = clone.header.previous = clone.header;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Entry<E> e = header.next; e != header; e = e.next)
            clone.add(e.element);

        return clone;
    }

    public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Entry<E> e = header.next; e != header; e = e.next)
            result[i++] = e.element;
        return result;
    }

    public <T> T[] toArray(T[] a) {//如果a的长度小于siz(不能容纳下)用反射创建一个新的数组大小为size,由result引用,向其遍历加入节点后,
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Entry<E> e = header.next; e != header; e = e.next)
            result[i++] = e.element;

        if (a.length > size)//如多比size大,其余部分补空
            a[size] = null;

        return a;
    }

    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Entry e = header.next; e != header; e = e.next)
            s.writeObject(e.element);
    }

    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        // Initialize header
        header = new Entry<E>(null, null, null);
        header.next = header.previous = header;

        // Read in all elements in the proper order.
        for (int i=0; i<size; i++)
            addBefore((E)s.readObject(), header);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值