Consider a singly linked list.
First Node : value=v1,address of this node=x,next=y ;
Second Node : value=v2,address of this node=y,next=NULL
Linked list pointer *ptr=x;
Linked list pointer *ptr1=y;
ptr1->next=ptr; // This is wrong
This will show the error of "heap-use-after-free"
WHY I can't store the address of 2 nodes in each other?
ptr->next=NULL // or any other node address
ptr1->next=ptr; // This is right
I can use this but why I can not use the above one?
(I don't need to traverse to the end and you can assume there are a lot of nodes)
What I have tried:
CODE FOR BETTER UNDERSTANDABILITY OF QUESTION
This is showing error why?
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *a,*b,*c;
a=head;
if(!a)
return a;
a=head->next;
b=head->next->next;
while(b!=NULL)
{
c=b->next;
b->next=a;
a=b;
b=c;
}
head->next=NULL;
return a;
}
now below one is correct
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *a,*b,*c;
a=head;
if(!a)
return a;
b=head->next;
head->next=NULL;
while(b!=NULL)
{
c=b->next;
b->next=a;
a=b;
b=c;
}
return a;
}
};