LeetCode 21 合并两个有序链表 c语言

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        // 类似归并排序中的合并过程
        struct ListNode *Head = malloc(sizeof(struct ListNode));//建立头结点
        struct ListNode *curr = Head;
    
        while (l1 != NULL && l2 != NULL) {
            if (l1->val < l2->val) {
                curr->next = l1;
                curr = curr->next;
                l1 = l1->next;
            } else {
                curr->next = l2;
                curr = curr->next;
                l2 = l2->next;
            }
        }
        // 任一为空,cur则指向另一链表的最后一个值
        if (l1 == NULL) 
            curr->next = l2;
        else 
            curr->next = l1;
        return Head->next;
}



猜你喜欢

转载自blog.csdn.net/Yupppppi/article/details/88901007