[LeetCode 21] Merge Two Sorted Lists

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.

Diffculty
Easy

Similar Problems
[LeetCode ] Merge k Sorted Lists Hard [LeetCode ] Merge Sorted Array Easy [LeetCode ] Sort List Medium [LeetCode ] Shortest Word Distance II Medium

Analysis

/**

  • Definition for singly-linked list.
  • struct ListNode {
  • int val;
  • ListNode *next;
  • ListNode(int x) : val(x), next(NULL) {}
  • }; */

// 8ms

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode(-1);;
        auto p = head;
        while(l1 != nullptr && l2 != nullptr){
            if(l1->val < l2->val){
                p->next = l1;
                l1 = l1->next;
            }
            else{
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if(l1 != nullptr)
            p->next = l1;
        if(l2 != nullptr)
            p->next = l2;
        p = head->next;
        delete head;
        return p;
    }
};

results matching ""

    No results matching ""