Reverse a Linked-List
Question: Reverse a Linked-list. Write code in C.
Answer: There are multiple ways to go about this. Let’s first look at a recursive solution.
Node * reverse( Node * ptr , Node * previous) { Node * temp; if(ptr->next == NULL) { ptr->next = previous; return ptr; } else { temp = reverse(ptr->next, ptr); ptr->next = previous; return temp; } } reversedHead = reverse(head, NULL);
Now for a non-recursive solution.
Node * reverse( Node * ptr ) { Node * temp; Node * previous = NULL; while(ptr != NULL) { temp = ptr->next; ptr->next = previous; previous = ptr; ptr = temp; } return previous; }
I personally prefer the non-recursive solution but it is always good to know both of them.
Comments
Post a Comment