Merge Two Sorted Linked Lists

mail@pastecode.io avatar
unknown
c_cpp
20 days ago
2.3 kB
2
Indexable
Never
/**
 * 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* newList;
        ListNode* newListHead;

        if(!list1 && !list2)
            return list1;
        if(!list1)
        {
            newList=list2;
            newListHead=newList;
            list2=list2->next;
        }
        else if(!list2)
        {
            newList=list1;
            newListHead=newList;
            list1=list1->next;
        }
        else
        {
            if(list1->val>list2->val)
            {
                newList=list2;
                list2=list2->next;
            }
            else
            {
                newList=list1;
                list1=list1->next;
            }
            newListHead=newList;
        }

        while(list1 || list2)
        {
            newList->next=nullptr;
            if(!list1)
            {
                newList->next=list2;
                list2=list2->next;
                newList=newList->next;
            }
            else if(!list2)
            {
                newList->next=list1;
                list1=list1->next;
                newList=newList->next;
            }
            else
            {
                if(list1->val>list2->val)
                {
                    newList->next=list2;
                    list2=list2->next;
                    newList=newList->next;
                }
                else if(list1->val<list2->val)
                {
                    newList->next=list1;
                    list1=list1->next;
                    newList=newList->next;
                }
                else
                {
                    newList->next=list1;
                    list1=list1->next;
                    newList=newList->next;
                    newList->next=list2;
                    list2=list2->next;
                    newList=newList->next;
                }
            }

        }

        return newListHead;
    }
};
Leave a Comment