c - reverse a linkedlist recursively -
my linkedlist reverse function gives correct result. am
confused.
linked list= 12->5->4->3 per reverse function result should 4->5->12 fortunately produces correct reversed list 3->4->5->12. pls me understand happening //head_ref global variable struct n* reverse(struct n *head){ struct n *pre,*cur; //temp variable first , second node if(head->next==null){ head_ref = head; // head_ref global variable initialized head pointer return; } pre = head; cur = head->next; reverse(cur); cur->next = pre ; pre->next = null; }
first call pre = 12 cur = 5 second call pre = 5 cur = 4 3rd call pre = 4 cur = 3
3->next = null //base condition fullfilled exit ( 3rd call ) reverse start second call pre = 5 cur = 4
my reversed linked list should 4->5->12
but produces 3->4->5->12 (correct reversed linked list)
why gives correct result. pls explain????
let start linked list 12->5->4->3
. when main (or other calling function) calls reverse function, head has data 12. following stack created after forth call reverse function.
| | |___________________________________________| gonna |__*head=3 *head->next=null__head_ref=3_____| => popped out |__*head=4 pre=4 curr=3_____________________| |__*head=5 pre=5 cur=4______________________| main calls=>|__*head=12_pre=12 cur=5____________________|
as said, clear above figure. when have head->next = null, top-most entry in stack gets popped out , 1 *head=4, pre=4 , curr=3 becomes topmost entry in stack. curr->prev evaluates 3->next=4 , 4->next->null.
| | | | popped out=> |______________________________________________________| |__*head=4 pre=4 curr=3__(3->next)=4__(4->next)=null___| |__*head=5 pre=5 cur=4_________________________________| |__*head=12_pre=12 cur=5_______________________________|
then entry *head=4 pre=4 curr=3__(3->next)=4__(4->next)=null pops out , same thing happens.
| | | | | | popped out=> |______________________________________________________| |__*head=5 pre=5 cur=4____(4->next)=5___(5->next=null)_| |__*head=12_pre=12 cur=5_______________________________|
in remaining 1 entry can see 12->next becomes null, 12 becomes tail of linked list.
| | | | | | | | popped out=> |______________________________________________________| |__*head=12_pre=12 cur=5__(5->next)=12_(12->next)=null_| | | | | | | | | | | popped out=> |______________________________________________________|
stack becomes empty , final linked list has 3 head , 12 tail:3->4->5->12
Comments
Post a Comment