代码在执行时挂起。请帮我理解这里有什么问题 它在第一次遍历后停滞,甚至没有进入反向功能。无法理解这个问题: 帮助我。
# include<iostream>
# include<stdlib.h>
using namespace std;
struct sLL
{
int data;
sLL * next;
};
void createList(sLL ** head, int n)
{
if(n == 0)
{
return;
}
sLL * temp = (sLL *) malloc(sizeof(sLL));
if(temp != NULL)
{
temp->data = rand() % 100;
temp->next = NULL;
*head = temp;
//head = &(temp->next);
createList(&(temp->next), n - 1);
}
}
void traverse(sLL * head)
{
cout<<"In traverse"<<endl;
while(head) {
cout<<head->data<<"->";
head=head->next;
}
cout<<"NULL"<<endl;
cout.flush();
return;
}
sLL* reverse(sLL * head)
{
sLL * temp = NULL, * newNode = NULL;
while(head) {
newNode = head->next; // to traverse forword
head->next = temp;
temp = head; // Current node value which we use in next itr as a previous node value.
newNode = head; // assigning newNode vlaue back to head so that we can traverse forward.
}
return temp; // final node value will be in temp i.e the current node value.
}
int main()
{
int n;
sLL * head = NULL, *temp = NULL;
cout<<"Enter the number of nodes :";
cin>>n;
createList(&head, n);
cout<<"\nCreate Done"<<endl;
traverse(head);
cout.flush();
cout<<"Reverse Start";
temp = reverse(head);
cout<<"reverse done";
traverse(temp);
}
答案 0 :(得分:1)
您根本不会重新分配头部值
while(head)
//loop
这里,头指针永远不会改变。所以循环是无限的。
答案 1 :(得分:0)
您的评论与此处的代码相矛盾:
newNode = head; // assigning newNode vlaue back to head so that we can traverse forward.
如果您执行评论所说的内容应该会更好:
head = newNode; // assigning newNode value back to head so that we can traverse forward.