Leetcode #21 Merge Two Sorted Lists

Posted by blueskyson on March 28, 2022

Description

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    struct ListNode *head;
    struct ListNode **cursor = &head;
    
    for (struct ListNode **node; list1 && list2;
         *node = (*node)->next) {
        node = (list1->val < list2->val) ? &list1 : &list2;
        *cursor = *node;   
        cursor = &(*cursor)->next;
    }
    
    *cursor = list1 ? list1 : list2;
    return head;
}

Runtime: 4 ms, faster than 74.01% of C online submissions for Merge Two Sorted Lists.

Memory Usage: 6.2 MB, less than 28.24% of C online submissions for Merge Two Sorted Lists.