簡體   English   中英

使用遞歸打印的鏈表問題

[英]Linked list Issue with printing using recursion

任何人都可以指出打印列表中的這種遞歸可能有什么問題嗎? 我得到無限期打印的最后一個元素。

class Node
{
    public:
    Node* next;
    int data ;
    
     Node()
    {
        this->data = 0;
        this->next = NULL ;
    }
Node add(int data)
{
    Node* node_t;
    node_t = new Node();
    node_t->data = data;
    node_t->next = NULL;
    this->next = node_t ;
            
}
    void print_list()
    {
        cout<<"data in list is "<< this->data << endl ;
        while(this->next != NULL)
            this->next->print_list();
    }

因此,在成員 function print_list() 中,您使用了一個 while 循環。

void print_list()
{
    cout<<"data in list is "<< this->data << endl ;
    while(this->next != NULL)
        this->next->print_list();
}

但想法是因為你在這里使用了一個循環,每個節點都會無限期地調用 function,因為next變量NULL永遠不會被分配任何其他東西,所以你將繼續打印第二個元素。

所以你的 function 應該是這樣的:

void print_list() {
        cout<<"data in list is "<< this->data << endl;
        if (this->next != NULL)
                this->next->print_list();
}

還有這個:

void add(int data)
{
    Node* node_t;
    node_t = new Node();
    node_t->data = data;
    node_t->next = NULL;
    this->next = node_t ;
            
}

應該是:

void add(int data)
{   
    Node* node_t;
    Node* last = this;
    while(last->next)
            last = last->next;
    node_t = new Node();
    node_t->data = data;
    node_t->next = NULL;
    last->next = node_t ;
}

或者,如果你真的喜歡遞歸:

void add(int data)
{
    Node* last = this;
    if (next)
            return next->add(data);
    Node* node_t;
    node_t = new Node();
    node_t->data = data;
    node_t->next = NULL;
    last->next = node_t ;
}

因為如果你不 append 到最后一個元素,你最終會重寫第二個元素,這也會導致 memory 泄漏。

我也希望你有一個析構函數來釋放你分配的所有 memory。

編輯:我注意到,對於沒有返回語句的方法,您有一個非 void 返回類型。 確保您返回某些內容或返回類型為無效。

暫無
暫無

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

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