Reverse Singly linked list, METHOD 1, RECURSIVE (head declared in main)
SinglyLinkedListNode* head, *nextp, *temp2;
SinglyLinkedListNode*reverse(SinglyLinkedListNode* temp)
{
if(temp->next==0)
{
temp2=temp;
return temp2;
}
head=reverse(temp->next);
//Now, head will contain the address of last node.
nextp=temp->next;
nextp->next=temp;
temp->next=0;
return head;
//Value of head will remain same, and same will be returned back and back
//and same back to main from where reverse is called.
}
int main()
{
.....
....
head=reverse(head);
//or could use new head variable.
//head1=reverse(head);
.....
.....
}
Comments
Post a Comment