让链表为 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 的函数
- 在 reverse(&1) 中,代码一直运行到 rev_head=reverse(&2); // 这里&1是1的地址。
函数列表是
1(first)->2(second) -> 3 -> 4
内部 reverse(&2) 代码运行直到 rev_head=reverse(&3); 功能列表
2(first)->3 (second)-> 4
内部 reverse(&3) 代码运行直到 rev_head=reverse (&4); 列出函数
3(first)-> 4(second)
内部 reverse(&4) 终止条件 second==NULL 为真,因此执行 return 并返回 4 的地址。
功能列表
4(第一)-> NULL(第二)
- 返回 reverse(&3) 函数列表为
NULL<-3(first) 4 (second)
并且返回的 rev_head=&4 的值
执行第二个->下一个=第一个后;列表变成
NULL<- 3(第一)<-4(第二)
返回(rev_head);执行通过 &4 因为 rev_head=&4
函数中的列表是
NULL<-2(第一)3(第二)<-4
rev_head 是 &4 由 rev(&3) 返回
执行 second->next=first 后,列表变为
NULL<-2(第一)<-3(第二)<-4
返回(rev_head);执行返回 &4 到 rev(&1);
函数中的列表是
NULL<-1(第一)2(第二)<-3<-4
rev_head 的值为 &4,由 reverse(&3) 传递
现在执行 second->next =first 并且列表变为
NULL<-1(第一)<- 2(第二)<-3<-4
返回(rev_head);执行 // rev_head=&4 由 reverse(&2) 返回,并将 rev_head 的值传递给主函数。
希望这可以帮助。我花了很多时间来理解这一点并写下这个答案。