I was trying to solve merge two sorted linked list problem from leetcode.
I solved the problem but here's something which I'm not understanding, When I try to create nodes and their pointers using 'new' keyword(which stores the nodes in heap memory) it works, but when I change it to first creating node and then creating a pointer to it then it shows "stack-use-after-scope".
Here's the commented code-
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
// ListNode *res = new ListNode() works but this doesn't
ListNode dummy(0);
ListNode *res = &dummy;
// just comparing the initial 2 values of both linked list-
if(l1->val<l2->val){
res->val=l1->val;
l1=l1->next;
}else{
res->val=l2->val;
l2=l2->next;
}
// head variable is to store the head of resultant linked list-
ListNode *head;
head=res;
// while both list contains elements-
while(l1!=NULL && l2!=NULL){
// ListNode *x = new ListNode() works but this doesn't
ListNode y(0);
ListNode *x = &y;
if(l1->val<l2->val){
x->val=l1->val;
l1=l1->next;
}else{
x->val=l2->val;
l2=l2->next;
}
res->next = x;
res = x;
}
// if list1 has some elements left-
while(l1!=NULL){
// ListNode *x = new ListNode() works but this doesn't
ListNode y(0);
ListNode *x = &y;
x->val=l1->val;
res->next=x;
res=x;
l1=l1->next;
}
// if list2 has some elements left-
while(l2!=NULL){
// ListNode *x = new ListNode() works but this doesn't
ListNode y(0);
ListNode *x = &y;
x->val=l2->val;
res->next=x;
res=x;
l2=l2->next;
}
return head;
}
Can anyone please help?