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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -