I have spent a lot of time on it but still getting the same error. Please someone help. I have written this code for a leetcode question.(merging two linked lists) have read many similar answers but still cannot figure out
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* third = NULL; ListNode* last = NULL; if (l1 && l2) { if (l1->val < l2->val) { third = last = l1; l1 = l1->next; last->next = NULL; } else { third = last = l2; l2 = l2->next; last->next = NULL; } } while (l1 && l2) { if (l1->val < l2->val) { last->next = l1; last = l1; l1 = l1->next; last->next = NULL; } else { last->next = l2; last = l2; l2 = l2->next; last->next = NULL; } } if (l1) { last->next = l1; } if (l2) { last->next = l2; } return third; } };
You only set last to a non-null value if both inputs are non-null.
last
You need to check it first, for instance with
if (last) { last->next = l1 ? l1 : l2; }
1.4m articles
1.4m replys
5 comments
57.0k users