簡體   English   中英

鏈接列表添加CPP

[英]Link list Adding CPP

我正在用cpp實現鏈接列表,以下代碼有什么問題? 每次我進入功能--- AddToTail時,“列表”都無法獲得正確的值。 它將其值更改為新構造的節點。

#include <iostream>
using namespace std;

struct Node
{
    int value;
    Node * next;
};

void AddToTail(Node* &list, int value)
{
    Node  newnode;
    newnode.value = value;
    newnode.next = NULL;

    if (list == NULL)
        list = &newnode;
    else
    {
        Node * list1 = list;
        while (list1->next != NULL)
        {
            list1 = list1->next;
        }
        list1->next = &newnode;
        int a = 1;
    }
}
int main()
{
    Node *list=NULL;

    AddToTail(list, 1);
    AddToTail(list, 2);
    AddToTail(list, 3);

    while (list->next != NULL)
    {
        cout << list->value << endl;
        list = list->next;
    }
    system("pause");
}
void AddToTail(Node* &list, int value)
{
    Node  newnode;
    // Set up fields of newnode.
    // Store address of newnode into some other data structure.
}

這是你的問題。 您正在堆棧上創建一個節點,該節點將在函數末尾超出范圍。 它似乎干擾以后的節點創建的原因是因為重新輸入該函數幾乎可以肯定會在與上一次調用完全相同的地址處創建newnode

如果您希望對象在功能范圍內生存,則需要動態分配它們,例如:

void AddToTail (Node *&list, int value) {
    Node *newnode = new Node();             // create on heap.
    newnode->value = value;                 // set up node.
    newnode->next = nullptr;

    if (list == nullptr) {                  // list empty,
        list = newnode;                     //   just create.
        return;
    }

    Node *lastNode = list;                  // find last item.
    while (lastNode->next != nullptr)
        lastNode = lastNode->next;
    lastNode->next = newnode;               // append to that.
}

暫無
暫無

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

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