美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: weego | 来源:发表于2018-04-06 08:36 被阅读0次

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

Solution

合并两个有序链表,保证结果仍然有序,easy

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    auto p = l1, q = l2;
    auto dummy = new ListNode(-1), pNode = dummy;
    while (p || q) {
        if (p == NULL) {
            pNode->next = q;
            return dummy->next;
        }
        if (q == NULL) {
            pNode->next = p;
            return dummy->next;
        }
        if (p->val < q->val) {
            pNode->next = p;
            p = p ->next;
        } else {
            pNode->next = q;
            q = q->next;
        }
        pNode = pNode->next;
    }
    return dummy->next;
}

相关文章

网友评论

      本文标题:21. Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/dcpjhftx.html