+ 3
I don't get the logic behind reversing a linked list
 void recursiveReverse(struct Node** head_ref) { struct Node* first; struct Node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; recursiveReverse(&rest); first->next->next = first; first->next= NULL; *head_ref = rest; }
2 Respuestas
+ 5
void recursiveReverse(struct Node** head_ref)
{
struct Node* first; // Stores first element.
struct Node* rest; // Stores rest of list.
if (*head_ref == NULL) return;
first = *head_ref;
rest = first->next;
if (rest == NULL) return;
recursiveReverse(&rest);
// This reverses the rest part of the list.
first->next->next = first;
// first->next->next is rest's last element,
// which is now linked to first to complete
// the reversal. Then to complete the list,
// we assign the next of first as NULL.
first->next= NULL;
*head_ref = rest;
// Now the list is reversed, but head
// still points in opp order, so we assign
// it with rest.
}
Here is a graphical representation for 2 links:
=> 1->2->NULL
// Original List.Assume 1 as first and
// 2 as rest.
Operation : first->next->next=first;
=> 1<-2
// Last element of rear has its next
// pointing to first now.
Operation : first->next=NULL;
=> NULL<-1<-2
//Assigned first's next as null. Now
// first is the last element.
+ 5
@Paul Victor
Can you please stop spoiling other's posts?