LeetCode-21. Merge Two Sorted Lists(2つの秩序チェーンテーブルをマージ)

5893 ワード

2つの順序付きチェーンテーブルを結合
2つの順序付きチェーンテーブルを新しい順序付きチェーンテーブルに結合して返します.新しいチェーンテーブルは、指定された2つのチェーンテーブルのすべてのノードを接合することによって構成されます.
例:
入力:1->2->4、1->3->4出力:1->1->2->3->4->4
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode a, *p = &a;
    a.next = NULL;
    while(l1 != NULL || l2 != NULL){
        struct ListNode *node = (struct ListNode *)malloc(sizeof(*node));
        node->next = NULL;
        p->next = node;
        p = node;
        if(l1 != NULL){
            if(l2 != NULL){
                if(l1->val < l2->val){
                    node->val = l1->val;
                    l1 = l1->next;
                }else{
                    node->val = l2->val;
                    l2 = l2->next;
                }
            }else{
                node->val = l1->val;
                l1 = l1->next;
            }
        }else{
            node->val = l2->val;
            l2 = l2->next;
        }
    }
    return a.next;
}