让我们来看一个链表:
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成立,所以执行返回语句,
返回地址为4的位置。
函数列表
4(first)-> NULL(second)
- 回到reverse(&3)
函数列表为
NULL<-3(first) 4 (second)
rev_head的值为被返回的&4
执行second->next=first; 后,链表变为
NULL<- 3(first) <-4 (second)
执行return (rev_head ); 将&4传递给rev(&2),因为rev_head=&4
函数列表为
NULL<-2(first) 3(second)<-4
rev_head的值为被reverse(&3)返回的&4
执行second->next=first 后,链表变为
NULL<-2(first)<-3(second)<-4
执行return(rev_head); // rev_head=&4,这是由reverse(&2)返回的
将rev_head的值传递给rev(&1);
函数列表为
NULL<-1(first) 2(second)<-3<-4
rev_head的值为被reverse(&3)传递的&4
现在执行second->next =first,链表变为
NULL<-1(first) <- 2(second)<-3<-4
执行return(rev_head); // rev_head=&4,这是由reverse(&2)返回的
将rev_head的值传递给主函数。
希望这有所帮助。我花了很多时间才理解这个问题并写出这个答案。
1->2->null
。为了使其通用,我们将始终从first
节点引用其他节点。要反转它,设置first(1)->next(2)->next(null) = first(1)
使其变成1<->2
,然后first(1)->next(2) = null
将导致null<-1<-2
。递归使用此规则。 - SMUsamaShah