【问题标题】:How to make recursive singly linked list (C++) [closed]如何制作递归单链表(C++)[关闭]
【发布时间】:2016-11-05 19:27:06
【问题描述】:

我的书要求我对单链表进行递归定义。我完全不知道该怎么做。有人可以帮我提供样品吗?谢谢

【问题讨论】:

  • 我不知道我的问题能得到多少详细信息。我在问题中提出的具体问题是我想知道的。我不知道为什么你们必须对一个问题如此具体。这个论坛是用来提问的,但是当我提问时,我的问题似乎总是有问题。

标签: c++ recursion singly-linked-list


【解决方案1】:

它就像一个普通的链表,只是迭代是通过递归而不是循环来执行的。

首先,一点点阅读:What is recursion and when should I use it?

例如,查找最后一个节点的基于循环的函数可以是:

Node * getLast(Node * current)
{
    while (current->next == null)
    { // loop until no more nodes
        current = current.next;
    }
    return current; // return last node
}

而递归版本只检查当前节点是否是最后一个节点,如果有下一个节点,则用下一个节点调用自身。

Node * getLast(Node * current)
{
    if (current->next == null)
    { // found last node. return it
        return current;
    }
    else
    { // see if next node is last node
        return getLast(current->next);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2019-08-13
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多