Linked Listの四つのエルゴード方法

2959 ワード

ArayListとLinkdListのget(),add(),remove()の3つの方法を比較する効率実験(メガクラス)で発見された:
普通のfor循環を使ってget Linked Listの中の元素を作る時、初めからget(index)の効率が非常に低いので、反復LinkdListの様々な方法を研究します。方法は以下の通りです。https://blog.csdn.net/The_Best_Hacker/article/details/81368079)
ここにまずLinked Listのgetを貼って、remove方法の下の階で実現します。
get:
    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        return entry(index).element;
    }
    private Entry entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry e = header;
        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;
    }
 remove:
    /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        return remove(entry(index));
    }
    private E remove(Entry 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;
    }
 getとremoveは毎回最初からやり直すか、最後から該当indexのelementを遍歴するので、いらないアイテムを遍歴するので、itemの数が増えるにつれて、簡単なforサイクルで効率が低下します。時間複雑度:(1+0.5 N)*0.5 N=O(N^2)
 
  • ローズマリーで
  • を巡回しました。
  • 用リスト・ディケンサは
  • を巡回しました。
  • はsize()、get(
  • )を巡回しました。
  • 拡張forで
  • を巡回しました。
    1.ローズマリーで巡回
    Iterator iterator=students.iterator();
            while(iterator.hasNext()){
                System.out.println(iterator.next());
            }
    2.リストを使って、ディケンサを巡回します。 
     ListIterator listIterator=students.listIterator();           
          while(listIterator.hasNext()){
               System.out.println(listIterator.next());       
          }
    
    
    3.サイゼ()、get()で遍歴します。
    for(int i=0;i
    4.拡張for巡回
    for(Student str:students){
                System.out.println(str.getName()+"-->"+str.getAge());
            }