AmericanSuave
AmericanSuave

Reputation: 373

Returning last node in linked list recursively

I'm trying to write function that returns the last node of a linked list recursively withour declaring any local variables. Is this right?

ListNode* lastPtr(ListNode* list){
If(list = NULL)
Return NULL;
Else 
List = lastPtr(list->next);
If(list->next = NULL)
Return list;
}

language is c++

Upvotes: 0

Views: 1286

Answers (2)

wildplasser
wildplasser

Reputation: 44240

ListNode *lastPtr(ListNode* list) {
return (list && list->next) ? lastPtr(list->next) : list;
} 

Upvotes: 3

Cristian Holdunu
Cristian Holdunu

Reputation: 1918

the equal sign in C++ is, as in C, and Java is == and not =

Try to correct your code.

ListNode * lastNode(ListNode *list)
{
    if (list!=NULL)
    {
        if (list->next==NULL)
            return list;
        else return lastNode(list->next);
    }
    else return NULL;
}

Upvotes: 1

Related Questions