簡體   English   中英

鏈表引發無限循環,但最新指針設置為null

[英]Linked list is throwing an infinite loop, yet latest pointer is set to null

我已經寫了一個鏈表,當我進行追加到末尾時,它似乎陷入了無限循環。

// this function will make a node and give it a value at the end of the list
void add_at_end(struct Node* begin, int v) {
    // new node
    struct Node* temporary = begin; // pointer to start of list
    temporary->vv = v;
    temporary->nx = NULL; // latest node
    if (begin == NULL) { // this will make a new list if it is empty
        begin = temporary;
        return;
    }
    struct Node* iterate = begin;
    while (iterate->nx != NULL) { iterate = iterate->nx; }
    iterate->nx = temporary;
    return;
}

我稱它為:

struct Node alpha;
add_at_end(&alpha, 1);

為什么會引發無限循環?

  • alpha不初始化,它包含垃圾內容,包括下一個指針。 訪問內容是不確定的行為,這可能導致無限循環...或崩潰..或其他任何原因。
  • begin = temporary; 這將在本地范圍內設置變量,並且對傳遞給函數的內容沒有任何影響。 您可以將指針傳遞給指針( ** ),也可以將現有節點傳遞給函數(在這種情況下,無需檢查)。 您正在混合這些沒有意義的內容。
  • 僅添加元素就遍歷整個列表是非常低效的。 您應該維護一個指向最后一個節點的鏈接,以使其成為O(1)操作。

暫無
暫無

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

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