LeetCode:21MergeTwoSortedList
题目描述:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
出错:访问空指针 member access within null pointer of type 'struct ListNode'
解决:优先考虑指针为空的情况避免访问出错
错误代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 ListNode rlt(-1); 13 ListNode *crt=&rlt; 14 while(l1!=NULL||l2!=NULL){ 15 if(l1==NULL||l1->val>l2->val){ 16 crt->next=l2; 17 l2=l2->next; 18 } 19 else if(l2==NULL||l1->val<l2->val){ 20 crt->next=l1; 21 l1=l1->next; 22 } 23 crt=crt->next; 24 } 25 return rlt.next; 26 } 27 };
其中第15行可能出现访问l2时l2文空指针的情况
解决方案如下:
1 class Solution { 2 public: 3 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 ListNode rlt(-1); 5 ListNode *crt=&rlt; 6 while(l1!=NULL||l2!=NULL){ 7 if(l1==NULL){ 8 crt->next=l2; 9 l2=l2->next; 10 } 11 else if(l2==NULL){ 12 crt->next=l1; 13 l1=l1->next; 14 } 15 else if(l1->val>l2->val){ 16 crt->next=l2; 17 l2=l2->next; 18 } 19 else{ 20 crt->next=l1; 21 l1=l1->next; 22 } 23 crt=crt->next; 24 } 25 return rlt.next; 26 } 27 };
或者:
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy(INT_MIN); ListNode *tail = &dummy; while (l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } tail->next = l1 ? l1 : l2; return dummy.next; } };

浙公网安备 33010602011771号