Я пишу эту функцию как часть домашней работы. Не было бы такой большой проблемы, если бы был включен хвостовой указатель, и большая часть кода была предоставлена моим инструктором и включена в объектный файл, поэтому у меня нет реализации, которую можно включить. Во всяком случае, по какой-то причине базовый случай в моей функции никогда не достигается. Может кто-нибудь сказать мне, почему это продолжает работать?
#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;
}
Ваше условие остановки не работает, потому что каждый раз, когда вы делаете рекурсивный вызов, вы начинаете с нового head
указатель. Итак, допустим, вы начинаете со связанного списка следующим образом:
При первом звонке вы проходите A
(ну, адрес A), и он проверяет, является ли A == B. Это не так, поэтому он выполняет рекурсивный вызов, передавая B. При этом вызове он проверяет, B == C. Это не удается, поэтому он делает рекурсивный вызов с передачей C. Это проверяет, является ли C == D. Сбой, поэтому он проверяет, D == E. Сбой, поэтому он проверяет, E == A. Сбой, поэтому он проверяет, A == B. Это по-прежнему не удается, так что продолжается …
И снова и снова это идет. Где это останавливается, никто не знает!
Других решений пока нет …