簡體   English   中英

反向鏈接列表(通過遞歸)不起作用

[英]Reversing a linked list (by recursion) not working

我試圖編寫代碼以反向鏈接列表,但輸出錯誤。 有什么我想念的嗎?

這是功能

void reverselinklist( struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL)
    {
        *headreverse = p;
        return;
    }

    reverselinklist(&(p->next));
    p->next->next = p;
    p->next = NULL;

}

后顯示功能

Input 409765
Output 4

*headreverse = p毫無意義。 您應該每次都設置*headreverse = p->next向前移動,直到到達最后一個節點。

無論如何,我更改了您的代碼以使其起作用:

void reverselinklist(struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL){
        return;
    }
    *headreverse = p->next;
    reverselinklist(headreverse);
    p->next->next = p;
    p->next = NULL;
}

對於單個列表,請使用兩個兩個指針,以更新列表,因為您無法返回。

這是我的代碼。 希望它能幫助您理解概念。

void reverselinklist(struct node** head_ref)
{
    struct node* first;
    struct node* rest;

    first = *head_ref; 
    rest  = first->next;

    if (rest == NULL)
       return;  

    reverselinklist(&rest);
    first->next->next  = first; 

    first->next  = NULL;         

    *head_ref = rest;             
}

如果可以,請提供建議。

您的headreverse沒有分配給列表的新標題。 確保為函數使用2個參數,1)初始列表的頭部2)當前節點(與headreverse相同)

if(p->next == NULL)
{
    *head = p; //instead of headreverse use head
    return;
}

暫無
暫無

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

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