[LeetCode] Merge Two Sorted Lists

来源:互联网 发布:雷诺数的特征长度知乎 编辑:程序博客网 时间:2024/06/15 09:38

★ 题目

https://leetcode.com/problems/merge-two-sorted-lists/description/

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->4Output: 1->1->2->3->4->4

★ 代码

208 / 208 test cases passed.Runtime: 3 ms
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    if (l1 == NULL) {        return l2;    }    if (l2 == NULL) {        return l1;    }    struct ListNode *result = NULL;    struct ListNode *last = NULL;    while (true) {        struct ListNode *n = NULL;        struct ListNode *n2 = NULL;        if (l1 != NULL && l2 != NULL) {            if (l1->val < l2->val) {                n = l1;                l1 = l1->next;            } else if (l1->val > l2->val) {                n = l2;                l2 = l2->next;            } else {                n = l1;                l1 = l1->next;                n2 = l2;                l2 = l2->next;            }            if (last == NULL) {                result = n;                last = n;            } else {                last->next = n;                last = n;            }            if (n2 != NULL) {                last->next = n2;                last = n2;            }        } else if (l1 != NULL) {            last->next = l1;            break;        } else if (l2 != NULL) {            last->next = l2;            break;        } else {            break;        }    }    return result;}
原创粉丝点击