设链表为
1-> 2 -> 3 ->4
c中的函数是--
struct linked_node * reverse_recursive(struct linked_node * head)
{
struct linked_node * first;/*stores the address of first node of the linked
list passed to function*/
struct linked_node * second;/* stores the address of second node of the
linked list passed to function*/
struct linked_node * rev_head;/*stores the address of last node of initial
linked list. It also becomes the head of the reversed linked list.*/
//initalizing first and second
first=head;
second=head->next;
//if the linked list is empty then returns null
if(first=NULL)
return(NULL);
/* if the linked list passed to function contains just 1 element, then pass
address of that element*/
if(second==NULL)
return(first);
/*In the linked list passed to function, make the next of first element
NULL. It will eventually (after all the recursive calls ) make the
next of first element of the initial linked list NULL.*/
first->next=NULL;
/* storing the address of the reverse head which will be passed to it by the
condition if(second==NULL) hence it will store the address of last element
when this statement is executed for the last time. Also here we assume that
the reverse function will yield the reverse of the rest of the linked
list.*/
rev_head=reverse(second);
/*making the rest of the linked list point to the first element. i.e.
reversing the list.*/
second->next=first;
/*returning the reverse head (address of last element of initial linked
list) . This condition executes only if the initial list is 1- not empty
2- contains more than one element. So it just relays the value of last
element to higher recursive calls. */
return(rev_head);
}
现在运行链表 1-> 2-> 3 -> 4 的函数
- 内反(&1)
代码一直运行到 rev_head=reverse(&2); // 这里&1是1的地址。
函数列表是
1(第一)->2(第二)-> 3-> 4
内反向(&2)
代码运行直到 rev_head=reverse(&3);
功能列表
2(第一)->3(第二)-> 4
内反向(&3)
代码运行直到 rev_head=reverse (&4);
列出 if 函数
3(第一)-> 4(第二)
内反向(&4)
终止条件 second==NULL 为真,因此执行 return 并
返回地址 4。
函数列表
4(第一)-> NULL(第二)
- 回退(&3)
函数列表是
NULL
以及返回的 rev_head=&4 的值
执行第二次后->next=first;
列表变成了
NULL
返回 (rev_head);被执行通过 &4 因为 rev_head=&4
函数中的列表是
NULL
而rev_head是&4,它是由rev(&3)返回的
执行 second->next=first 后,列表变为
NULL
return(rev_head);执行返回 &4 到 rev(&1);
函数中的列表是
NULL
rev_head 的值为 &4,由 reverse(&3) 传递
现在 second->next =first 被执行,列表变为
NULL
return(rev_head);被执行 // rev_head=&4 由 reverse(&2) 返回
并将 rev_head 的值传递给 main 函数。
希望这会有所帮助。我花了很多时间来理解这一点并写下这个答案。