gpt4 book ai didi

c++ - 使用递归反转链表的问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:31 25 4
gpt4 key购买 nike

我被要求编写一个驱动程序函数来调用递归函数。我想知道我需要在驱动程序函数中做什么。

这个程序是反转一个链表。

void invert_r()
{
//This is the driver function for recursive_invert

nodeType<Type> *p, *q;

q = first;
p = first;
recursive_invert(q, p);
}
nodeType<Type>* recursive_invert(nodeType<Type> *q, nodeType<Type> *p)
{
//Invert a linked list using recursion.
//DO NOT create any new node in your implementation
if(p -> link == NULL)
{
q -> link = p;
return p;
}
else
{
recursive_invert(p -> link, q) -> link = p;
}
return p;
}

最佳答案

void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;

/* empty list */
if (*head_ref == NULL)
return;

/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;

/* List has only one node */
if (rest == NULL)
return;

/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;

/* tricky step -- see the diagram */
first->next = NULL;

/* fix the head pointer */
*head_ref = rest;
}

关于c++ - 使用递归反转链表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19520404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com