簡體   English   中英

Java中的LinkedList

[英]LinkedList in java

我正在為一個分配編寫一個LinkedList類,並且正在編寫我的insert方法,想知道是否可以看一下它。

private Node first;     // start of the list

private class Node {
    private Item item;
    private Node next;
}

public boolean insert(Item item) {
    // add item to list if it doesn't already exist
    // return true if a new Node is created, otherwise false
    if ( first.next == null && first.item == item) {
        return false;
    }
    Node ptr = first;
    while (ptr.next != null) {
        if (ptr.item == item) {
            return false;
        }
        ptr = ptr.next;
    }
    Node oldFirst = first;
    first = new Node();
    first.item = item;
    first.next = oldFirst;
    return true;
}

在大多數情況下,我認為這還可以,但是每次嘗試跟蹤insert方法時,我最終都會感到困惑,並弄亂了所有引用更改。 有人可以告訴我我做對了嗎? 任何其他改進也將不勝感激。

我會考慮編寫一個額外的函數來檢查Item是否已經在列表中。 這將使插入功能更清晰,並且整個引用更改將僅在那兒。 也是您的第一個測試:

if ( first.next == null && first.item == item) {
    return false;
}

然后,僅執行while循環的第一次迭代。

您絕對應該首先進行初始化,以免引發@threenplusone所說的NullPointerExcpetion或檢查是否: first == null (如果first為null,則while循環中的第一個ptr.next會引發NPE)。此外,您還應按@Thilo所述,將項目進行相等比較。

其余的我認為是正確的。

您的insert方法不是OO-您正在使用while循環遍歷列表,因此該方法可以是static方法(如果您還傳入了第一個節點)。

一個更優雅的方法是:

用偽代碼:

insert(item) {
    if (next == null)
        add item to "this" // we are at end of list
    else
        next.insert(item) // hand item to the next node
}

暫無
暫無

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

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