[英]Linked list Issue with printing using recursion
Can anyone point out what might be the issue with this recursion in print list?任何人都可以指出打印列表中的这种递归可能有什么问题吗? I get the last element being printed indefinitely.
我得到无限期打印的最后一个元素。
class Node
{
public:
Node* next;
int data ;
Node()
{
this->data = 0;
this->next = NULL ;
}
Node add(int data)
{
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
this->next = node_t ;
}
void print_list()
{
cout<<"data in list is "<< this->data << endl ;
while(this->next != NULL)
this->next->print_list();
}
So in member function print_list() you use a while loop.因此,在成员 function print_list() 中,您使用了一个 while 循环。
void print_list()
{
cout<<"data in list is "<< this->data << endl ;
while(this->next != NULL)
this->next->print_list();
}
But the think is because you use a loop here, each node would call the function indefinitely, because the next
variable if NULL
, will never be assigned anything else, so you'll keep getting the second element printed.但想法是因为你在这里使用了一个循环,每个节点都会无限期地调用 function,因为
next
变量NULL
永远不会被分配任何其他东西,所以你将继续打印第二个元素。
So your function should look like that:所以你的 function 应该是这样的:
void print_list() {
cout<<"data in list is "<< this->data << endl;
if (this->next != NULL)
this->next->print_list();
}
Also this:还有这个:
void add(int data)
{
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
this->next = node_t ;
}
Should be that:应该是:
void add(int data)
{
Node* node_t;
Node* last = this;
while(last->next)
last = last->next;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
last->next = node_t ;
}
Or that, if you really like recursion:或者,如果你真的喜欢递归:
void add(int data)
{
Node* last = this;
if (next)
return next->add(data);
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
last->next = node_t ;
}
Because if you do not append to the last element, you'd end up rewriting the second element, which also causes a memory leak.因为如果你不 append 到最后一个元素,你最终会重写第二个元素,这也会导致 memory 泄漏。
I also hope you have a destructor to free all the memory you've allocated.我也希望你有一个析构函数来释放你分配的所有 memory。
Edit: I noticed, that you have a non void return type for methods that don't have a return statement.编辑:我注意到,对于没有返回语句的方法,您有一个非 void 返回类型。 Make sure you either return something or return type is void.
确保您返回某些内容或返回类型为无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.