[英]Linked list Issue with printing using recursion
任何人都可以指出打印列表中的这种递归可能有什么问题吗? 我得到无限期打印的最后一个元素。
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();
}
因此,在成员 function print_list() 中,您使用了一个 while 循环。
void print_list()
{
cout<<"data in list is "<< this->data << endl ;
while(this->next != NULL)
this->next->print_list();
}
但想法是因为你在这里使用了一个循环,每个节点都会无限期地调用 function,因为next
变量NULL
永远不会被分配任何其他东西,所以你将继续打印第二个元素。
所以你的 function 应该是这样的:
void print_list() {
cout<<"data in list is "<< this->data << endl;
if (this->next != NULL)
this->next->print_list();
}
还有这个:
void add(int data)
{
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
this->next = node_t ;
}
应该是:
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 ;
}
或者,如果你真的喜欢递归:
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 ;
}
因为如果你不 append 到最后一个元素,你最终会重写第二个元素,这也会导致 memory 泄漏。
我也希望你有一个析构函数来释放你分配的所有 memory。
编辑:我注意到,对于没有返回语句的方法,您有一个非 void 返回类型。 确保您返回某些内容或返回类型为无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.