我的代码有什么问题?我陷入了无限循环。
void createList(sLL ** head, int n)
{
cout<<"\nstart n :"<< n;
if(n == 0)
{
return;
}
sLL * temp = (sLL *) malloc(sizeof(sLL));
if(temp != NULL)
{
temp->data = rand() % 100;
temp->next = NULL;
*head = temp;
cout<<"\nI am thhere : "<<n;
createList(&(temp->next), n - 1);
cout<<"\nI am here : "<<n;
}
}
答案 0 :(得分:0)
您的列表生成代码看起来是正确的。但是,您的输出是缓冲的,因此,如果您认为代码被卡住了,那么它实际上并没有被卡住。相反,您的消息会卡在cout
缓冲中。
将cout
邮件修改为flush
cout
流。我已经演示了以下每种技术:
void createList(sLL ** head, int n)
{
cout<<"\nstart n :"<< n << endl; // endl operator flushes stream and gives a line break
if(n == 0)
{
return;
}
sLL * temp = (sLL *) malloc(sizeof(sLL));
if(temp != NULL)
{
temp->data = rand() % 100;
temp->next = NULL;
*head = temp;
cout<<"\nI am thhere : " << n << flush; // flush operator flushes the stream without an added line break
createList(&(temp->next), n - 1);
cout<<"\nI am here : "<<n;
cout.flush(); // alternately, you can flush cout directly. Also does not add a line break
}
}
如果您的代码挂起,则在代码中createList()
调用后的某个时间您尚未向我们展示。但是,因为cout
缓冲了它的消息,并且因为你没有刷新cout
,所以你的调试工作被误导了。