【发布时间】:2016-06-11 06:29:59
【问题描述】:
我的链表反向函数给出了正确的结果。但我是
困惑。
linked list= 12->5->4->3
as per my reverse function the result should be
4->5->12
but fortunately it produces the correct reversed list
3->4->5->12.
pls help me to understand what happening
//head_ref global variable
struct n* reverse(struct n *head){
struct n *pre,*cur; //temp variable for first and second node
if(head->next==NULL){
head_ref = head; // head_ref global variable initialized with head pointer
return;
}
pre = head;
cur = head->next;
reverse(cur);
cur->next = pre ;
pre->next = NULL;
}
第一次通话 前 = 12 电流 = 5 第二次通话 前 = 5 当前 = 4 第三次通话 前 = 4 cur = 3
3->next = NULL //base condition fullfilled
so it will exit ( 3rd call )
reverse will start from
second call
pre = 5
cur = 4
我的反向链表应该是4->5->12
但它产生 3->4->5->12(正确的反向链表)
为什么它会给出正确的结果。请解释一下????
【问题讨论】:
标签: c recursion linked-list