Search code examples
crecursionlinked-listsingly-linked-listfunction-definition

Linked List Recursive Function


You're given a linked list 1->2->3->4->5->6->NULL. Why is the output as 1 3 5 5 3 1. I'm very confused, please explain the logic.

void fun(struct node *start){
    if(start==NULL){
        return;
    }
    printf("%d",start->data);
    if(start->next!=NULL)
        fun(start->next->next);
    print("%d",start->data);
}

Solution

  • You can see it in the pseudocode, if you execute it "in your head".

    fun([1,2,3,4,5,6,NULL])=> //Call fun with list
    print(1) //Print 1
    fun([3,4,5,6,NULL])=>
    print(3)
    fun([5,6,NULL])=>
    print(5)
    fun([NULL])=>
    <Do nothing as its next element is equals NULL>
    return from fun
    print(5)
    return from fun
    print(3)
    return from fun
    print(1)