I am implementing a function to recursively reverse a linked-list, but getting seg-fault.
typedef struct _node {
int data;
struct _node *next;
} Node, *NodeP;
NodeP recursiveReverseList(NodeP first){
if(first == NULL) return NULL;
if(first->next == NULL) return first;
NodeP rest = recursiveReverseList(first->next);
rest->next = first;
first->next = NULL;
return first;
}
Can you please help?
P.S. The iterative version is working fine though. Its not homework. Just practicing C.
Thank you all 🙂
@Unicornaddict has already posted a correct algorithm.
But, if you are still getting
segmentation fault, I suspect you are making some mistake in calling the function frommain.Correct:
Explanation:
head->nextto the recursive function. If you passhead, it will do something likewhich will make
headpoint toNULLandApoint toheadhead->nextas argument, state of the list is:So, you need to make
headpoint torest(Cin this case).