简体   繁体   中英

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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