Reversing a linkedlist recursively in c

后端 未结 9 1271
滥情空心
滥情空心 2020-12-07 23:33

The following code works fine when head is sent as a parameter to it. As I am new to C, I couldn\'t understand how it works. Help me out please.

struct node          


        
9条回答
  •  天命终不由人
    2020-12-07 23:55

    It seems to me that nobody has suggested an algorithm that is tail-recursive. In principle, a tail-recursive algorithm can be compiled without a stack (provided that the compiler is smart enough), thus producing code that consumes less memory.

    Assume TList is a custom data-type for single-linked list, it is a pointer to a structure that as a link field for accessing the next element in the list.

    The algorithm is the following:

    ```

    TList reverse_aux(TList l, TList solution) {
        if (l == NULL) {
            return solution;
        } else {
            TList tmp = l->link;
            l->link = solution;
            return reverse_aux(tmp, l);
        }
    }
    
    TList reverse(TList l) {
        return reverse_aux(l, NULL);
    }
    

    ```

提交回复
热议问题