首页 > 其他分享 >23/1/31-LeetCode 21: Merge Two Sorted Lists

23/1/31-LeetCode 21: Merge Two Sorted Lists

时间:2023-01-31 17:58:34浏览次数:62  
标签:ListNode 21 val 23 31 list1 next list2 cur

Merge Two Sorted Lists

思路

bug

注意,一开始我写的是

ListNode *ans, *cur;
if(list1->val <= list2->val)
{
	ans = cur = list1;
	list1 = list1->next;
}
else{
	ans = cur = list2;
	list2 = list2->next;
}

就是没有对指针进行NULL判断,试图对空指针进行操作 Line xx: Char xx: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:24:19LeetCode进行报错。

所以对指针操作之前要进行判断,判断是否为空指针。

实现

method1:自定义一个headnode

直接整个while,整体进行大小判断;
最后再returnheadnode->next;

/**
 * Definition for singly-linked list.
 * 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) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode *ans, *cur;
        ans = cur = new ListNode(0);
        
        while(list1 && list2)
        {
            if(list1->val <= list2->val)
            {
                cur->next = list1;
                list1 = list1->next;
            }
            else{
                cur->next = list2;
                list2 = list2->next;
            }
            cur = cur->next;            
        }
        if(list1) cur->next = list1;
        else cur->next = list2;
        return ans->next;
    }
};

method2:先找到头结点属于list1还是list2

/**
 * Definition for singly-linked list.
 * 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) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode *ans, *cur;
        if(!list1) return list2;
        else if(!list2) return list1;
        
        if(list1->val <= list2->val)
        {
            ans = cur = list1;
            list1 = list1->next;
        }else{
            ans = cur = list2;
            list2 = list2->next;
        }
        //ans = cur = new ListNode(0);
        while(list1 && list2)
        {
            if(list1->val <= list2->val)
            {
                cur->next = list1;
                list1 = list1->next;
            }
            else{
                cur->next = list2;
                list2 = list2->next;
            }
            cur = cur->next;            
        }
        if(list1) cur->next = list1;
        else cur->next = list2;
        return ans;
    }
};

标签:ListNode,21,val,23,31,list1,next,list2,cur
From: https://www.cnblogs.com/sectumsempra/p/17079516.html

相关文章