【问题标题】:Recursively compute the number of nodes in a circular linked list given only head pointer仅给定头指针,递归计算循环链表中的节点数
【发布时间】:2017-11-21 05:29:03
【问题描述】:

我正在编写这个函数作为作业的一部分。如果包含尾指针并且大部分代码由我的讲师提供并包含在目标文件中,那也没什么大不了的,所以我没有要包含的实现。无论如何,由于某种原因,我的函数中的基本情况永远不会达到。谁能告诉我为什么这一直在循环?

#include "clist.h"
#include <iostream>

using namespace std;

struct node
{
    int     data;
    node*   next;
};

//Iteratively compute and return the number of nodes in the circular linked list
int count(node* head)
{
    int nodeTotal = 1;
    node* temp = head;
    while(temp->next != head)
    {
        nodeTotal++;
        temp = temp->next;
    }
    return nodeTotal;
}


//Recursively compute and return the number of nodes in the circular linked list
int countR(node* head)
{
    node* temp = head;
    if(temp->next == head)
        return 0;
    else
        return 1 + countR(temp->next);
}


//Iteratively compute and return the sum of the ints contained in the circular linked list
int sum(node* head)
{
    int valuesTotal = 2;
    node* temp = head;
    while(temp->next != head)
    {
        valuesTotal += temp->data;
        temp = temp->next;
    }
    return valuesTotal;
}

int main()
{
    node* head{nullptr};

    /* Builds a circular linked list with a random number of nodes
    *containing randomly-chosen numbers.
    */
    build(head);

    display(head);  

    // PUT YOUR CODE HERE to call the functions assigned,
    // and print out the results. For example,
    //
    //    cout << "iterative sum: " << sum(head) << endl;
    //
    // The code for your functions should be in clist.cpp.
    cout << "\nIterative node count: " << count(head) << endl;
    cout << "Iterative sum: " << sum(head) << endl;
    cout << "Recursive node count: " << countR(head) << endl;

    // When called the 2nd time, this also prints the total
    // of the numbers in the nodes.
    display(head);




    int     nNodesFreed{0};
    node*   n{head};
    node*   temp;

    while( n != head || ! nNodesFreed) {
        temp = n->next;
        delete n;
        n = temp;
        nNodesFreed++;

        }
    cout << "# nodes freed: " << nNodesFreed << endl;

    //destroy(head);

    return 0;
}

【问题讨论】:

  • 您的错误应该很容易找到,并且列表相对较短,并且可以使用开发环境附带的调试器进行几次。
  • 如果递归永远不会停止,那么它当然会由于堆栈溢出而“seg fault”。那么你真正要问的是什么?
  • 我想知道为什么我的停止条件不起作用
  • @kbousman 我们需要minimal reproducible example,而不是代码 sn-ps。

标签: c++ recursion circular-list


【解决方案1】:

您的停止条件不起作用,因为每次进行递归调用时,都会从一个新的 head 指针开始。所以,假设你从一个这样的链表开始:

在第一次调用时,您传递 A(嗯,A 的地址),它会检查 A == B 是否。它没有,所以它执行一个递归调用传递 B。在那个调用中,它检查 B == C 是否失败,所以它通过 C 进行递归调用。 检查 C == D 是否失败,所以它检查 D == E 是否失败,所以它检查是否 E == A . 那失败了,所以它检查是否 A == B。那仍然失败,所以它继续...

它转来转去。它停在哪里,没人知道!

【讨论】:

  • 谢谢杰瑞,这很有帮助!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 2013-09-22
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
相关资源
最近更新 更多