简体   繁体   English

链接列表反向递归功能不起作用

[英]Link List Reverse Recursive Function Not Working

I'm unable to workout why my recursive function isn't working. 我无法锻炼为什么我的递归功能无法正常工作。 Everytime I run the code the linked list doesn't print in reverse. 每次我运行代码时,链表都不会反向打印。

typedef struct numberline NUMBERLINE; 
NUMBERLINE * startptr;
NUMBERLINE * newptr;
NUMBERLINE * curptr;

NUMBERLINE *revRecursive(NUMBERLINE *curptr)
{

    NUMBERLINE *q, *head;

    if(curptr->next == NULL)
    {
        return curptr;
    }

    head = curptr;

    q = curptr = revRecursive(curptr);

    while(q->next != NULL)
    {
        q = q->next;
    q->next = head;
    head->next = NULL;

    return curptr;
    }
}

Maybe I'm using the wrong pointer in the parameter, or I haven't implemented properly I'm unsure. 也许我在参数中使用了错误的指针,或者不确定我没有正确实现。

The function can look the following way 该函数可以如下所示

NUMBERLINE * reverse( NUMBERLINE *head ) 
{ 
    if ( head && head->next ) 
    { 
        NUMBERLINE *current = head; 
        head = head->next; 
        head = reverse( head ); 
        current->next->next = current; 
        current->next = NULL; 
    }

    return head;
} 

As for your function definition then even this statement 至于你的函数定义,那么即使这个语句

if(curptr->next == NULL)
{
    return curptr;
}

arises the undefined behavior when curptr is equal to NULL . curptr等于NULL时,出现不确定的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM