簡體   English   中英

firstLast Java鏈接列表/節點

[英]firstLast Java Linked list/nodes

我對每個節點如何鏈接到另一個節點感到困惑,以及如何確保如果我希望第一個節點在最后一個節點之后鏈接,我沒有運行無限循環。 例如,在這個問題..

編寫一個firstLast方法,可以將其添加到LinkedIntList類中,該類將列表的第一個元素移動到列表的后端。 假設名為list的LinkedIntList變量存儲從前(左)到后(右)的以下元素:

[18,4,27,9,54,5,63]如果您調用了list.firstLast();,那么列表將按以下順序存儲元素:

[4,27,9,65,5,63,18]如果列表為空或只有一個元素,則不應修改其內容。

我的第一次嘗試就是這樣做......但無濟於事:

`public void firstLast(){
    ListNode temp = front;//stores/references the first node
    temp.next = null;//ensures that first node isn't referring to any other 
//node
    ListNode current = front;//reaches end node/first one with a null 
//reference
    while(current.next != null){
        current = current.next;
    }
    front.next = temp;//links end node to first node
    front = current.next;////now that skips the first element`

但輸出是[18] -> [18] (cycles!) 請指教

函數firstLast()可以編碼如下:

public void firstLast()
{
    ListNode temp = removeFirst();
    appendLast( temp );
}

所以,現在你把問題分解為兩個較小的問題。 這往往是解決任何問題的非常好的策略。

您需要記住的一點是,為了實現您的removeFirst() ,您必須修改front指向第二個節點,即front.next

我對每個節點如何鏈接到另一個節點感到困惑

在單鏈表中,每個節點只知道下一個節點。 所以你需要跟蹤第一個,通常稱為head (在你的實現中它是“前面”),因為訪問所有元素是必不可少的。

...以及如何確保如果我希望第一個節點在最后一個節點之后鏈接,我沒有運行無限循環。

最后一個節點后面沒有下一個節點,因此它的next指針為null 您可以使用此條件來避免無限循環。 (只需確保最后一個節點next正確為null 。)

您的實施可以修復為:

public void firstLast() {
    // list is empty or has single element -> nothing to do
    if (front == null || front.next == null) {
        return;
    }

    // save the first
    ListNode first = front;

    // move the head
    front = front.next;

    // find the end
    ListNode current = front;
    while (current.next != null) {
        current = current.next;
    }

    // append the node
    current.next = first;

    // reset the next pointer of the new last node
    first.next = null;
}

鑒於您實施:

void push(ListItem item) {
    end.next = item;
    item.next = null;
}

ListItem pop() {
    ListItem first = front;
    front = front.next;
    return first;
}

你的方法變成:

void firstLast() {
    push(pop());
}

注意 :未經測試的代碼,不檢查空值或列表大小。

暫無
暫無

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

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