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

标签 c++ function recursion linked-list

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

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

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/

相关文章:

javascript - 哪个是定义函数的更好方法?

java - 递归地按升序打印整数

c - 堆的以下代码损坏是什么?

javascript - 如何以堆栈安全的方式映射树?

c++ - 致命字符串错误

c++ - 为什么 Cplex 提供了一个松弛约束的解决方案?

c - function() 中未指定的参数会发生什么?

c++ - 折叠表达式是 C++14 还是 C++1z 特性?

c++ - 哪个版本的 safe_delete 更好?

python - 完美序列化Python中的函数