簡體   English   中英

拆分Linkedlist實現“get方法”

[英]Realization of "get method" by splitting Linkedlist

我只是在研究 Linkedlist 主題並嘗試實現不同的功能,例如刪除、添加和獲取。

這是我從雙鏈表中獲取元素值的 get 方法的實現。 但是我在想的是通過拆分來使方法更有效。 如果我要查找第 77 個元素的值怎么辦? 從最后開始一定會更快。但是怎么做呢?

類似“if i>size/2 {}”之類的東西……但我被卡住了,找不到任何關於它的信息,也無法理解如何實現它。

public T get(int i) {
        if (i < 0 || i > size) {
            throw new IndexOutOfBoundsException();
        }
        Node<T> current = first;
        for (int a = 0; a < i; a++) {
            current = current.next;
        }
        return current.item;
    }

我想也許我應該把這部分帶到一個單獨的方法或者?

Node<T> current = first;
        for (int a = 0; a < i; a++) {
            current = current.next;

有可能嗎? 對於任何想法和幫助將不勝感激。

是的,理論上你可以拆分get(i)的情況,這樣如果索引大於列表的一半,你就從后面開始迭代。 但是,這在您的實施中有兩個先決條件:

  1. 您的實現需要有對頭部和尾部的引用(即就像你有first ,你也需要last
  2. 您的列表需要雙向鏈接,以便您可以向后遍歷它。 (即您應該能夠從last獲取倒數第二個元素)

如果您的實現中沒有涉及上述 2 項,我建議您先通過了解雙向鏈表來做這些。 上述更改也會影響您的add()remove()方法。

但是假設您已經涵蓋了這兩個,您可以將get(i)修改為這樣:

public T get(int i) {
    if (i < 0 || i > size) {
        throw new IndexOutOfBoundsException();
    }
    if (i <= this.length()/2) {                       // I assume you have a length method
        Node<T> current = first;
        for (int a = 0; a < i; a++) {
            current = current.next;
        }
        return current.item;
    } else {
        Node<T> current = last;                       // last is the reference to the tail as mentioned above
        for (int a = this.length()-1; a > i; a--) {
            current = current.previous;               // a double-linked list has nodes with references to previous elements as well
        }
        return current.item;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM