21. Merge Two Sorted Lists

    xiaoxiao2021-12-15  17

    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.

    合并两个链表。

    代码:

    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { if(!l1) return l2; if(!l2) return l1; if(l1->val > l2->val) { struct ListNode* tmp = l1; l1 = l2; l2 = tmp; } struct ListNode *ret = l1, *prev = l1; l1 = l1->next; while(l1 && l2) { if(l2->val < l1->val) { prev->next = l2; l2 = l2->next; prev->next->next = l1; } else { l1 = l1->next; } prev = prev->next; } if(l2) prev->next = l2; return ret; }

    转载请注明原文地址: https://ju.6miu.com/read-1000317.html

    最新回复(0)