I never normally post a question asking what is wrong with code, but I am a bit baffled here and don't see the reason a function below should fail.
I am writing a function to reverse a linked list. The first function ReverseList1() causes a runtime error and crashes when tested with the driver code form main().
The second function ReverseList2(), using a pointer to a pointer instead as the head argument works fine. Why, It is still pointing to the same data? Perhaps I am missing something obvious and crucial but I can't see it. Thanks in advance.
//// First function/////
void ReverseList1(struct Node* head, struct Node* prev, struct Node* next)
{
// not valid list
if (head == NULL)
{
return;
}
struct Node* cur = head;
while(cur != NULL)
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
head = prev;
}
//////// Second function - doesn't crash when use this////
void ReverseList2(struct Node** head, struct Node* prev, struct Node* next)
{
// not valid list
if (head == NULL)
{
return;
}
struct Node* cur = *head;
while(cur != NULL)
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*head = prev;
}
////// Driver code to test//////
int main()
{
struct Node* head= new struct Node;
head->data = 1;
head->next = new struct Node;
head->next->data = 2;
head->next->next = new struct Node;
head->next->next->data = 3;
head->next->next->next = new struct Node;
head->next->next->next->data = 4;
head->next->next->next->next = NULL;
//ReverseList1(head, NULL, NULL); // Runtime error
ReverseList2(&head, NULL, NULL)
cout<<head->data<<endl;
cout<<head->next->data<<endl;
cout<<head->next->next->data<<endl;
cout<<head->next->next->next->data<<endl;
return 0;
}