LeetCode 21. 合并两个有序链表 (c语言实现)

21. 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1
LeetCode 21. 合并两个有序链表 (c语言实现)_第1张图片

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

解题思路:

  • 归并排序的思想
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    //新链表的头尾指针
    struct ListNode* newHead = NULL;//制造新链表,赋予首尾指针
    struct ListNode* newTail = NULL;
    if(list1 == NULL){//list1为空链表时,保留list2
        return list2;
    }
    if(list2 == NULL){//list2为空时,保留list1
        return list1;
    }
    //确定第一个结点,头尾指针
    if(list1->val < list2->val) {
    //list1元素的值小于list2所指元素的值时,将新链表的头尾指针指向list1
        newHead = newTail = list1;
        list1 = list1->next;
    }else{
        newHead = newTail = list2;
        list2 = list2->next;
    }
    while(list1 && list2){   
        if(list1->val < list2->val){   
            newTail->next = list1;//尾插法实现增序
            newTail = list1;
            list1 = list1->next;
        }else{
            newTail->next = list2;
            newTail = list2;
            list2 = list2->next;   
        }
    }
    if(list1){//list1还有元素剩余,将剩余元素追加到新链表链尾就行
        newTail->next = list1;
    }
    if(list2){//list2还有元素剩余,将剩余元素追加到新链表链尾就行
        newTail->next = list2;
    }
    return newHead;//返回新链表
}

你可能感兴趣的:(LeetCode之链表篇,链表,leetcode,c语言)