力扣21題(C語言)合併兩個有序鏈表

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。在這裏插入圖片描述

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    Node* head =NULL;
    Node* tail =NULL;

    while(l1 && l2)
    {
        //取小的進行尾插
        if(l1->val <l2->val)
        {
            if(tail == NULL)
            {
                head = tail =l1;
            }
            else
            {
                tail->next = l1;
                tail = l1;
            }
            l1 = l1->next;
        }
        else
        {
            if(tail == NULL)
            {
                head = tail =l2;
                tail =l2;
            }
            else{
                tail->next =l2;
                tail =l2;
            }
            l2=l2->next;
            
        }
    }
    if(l1)
    {
        tail->next =l1;
    }
    else if(l2)
    {
        tail->next = l2;
    }
    return head;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章