pointers - Why does Infinite loop occurs while reversing the linked list using recursion -
i beginner in data structures. lets assume have linked list of 5 elements. writing below code reverse linked list using recursion:
void reverse (node* p) { if (p->next == null) { head = p; return; } reverse (p->next); node* q = p->next; q->next = p; p->next = null; }
in above code, head node passed argument. code runs well;but question why using line?
p->next = null;
if did not add line, becomes infinite loop. if line not added, p->next assigned previous node's address in following stack unwinding. why cause infinite loop if line not added?
Comments
Post a Comment