仅给出头指针

时间:2017-11-21 05:29:03

标签: c++ recursion circular-list

我将此功能作为家庭作业的一部分。如果包含尾部指针并且大部分代码都是由我的教师提供并包含在目标文件中,那么这将不是什么大问题,所以我没有包含的实现。无论如何,由于某种原因,我的函数中的基本案例永远不会到达。谁能告诉我为什么这会循环?

#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;
}

1 个答案:

答案 0 :(得分:1)

您的停止条件不起作用,因为每次进行递归调用时,都会以新的head指针开始。所以,让我们假设您从这样的链接列表开始: enter image description here

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

它绕而转。它停止的地方,没有人知道!