021 Merge Two Sorted Lists [Leetcode]

題目內容:

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.

解題思路:
很基礎的問題,注意處理長度不等的問題,同樣使用附加頭結點化簡處理。

非遞歸實現代碼如下,運行時間8ms:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if (l1 == NULL)
            return l2;
        if (l2 == NULL)
            return l1;

        ListNode *p1(l1), *p2(l2), *pre_head(new ListNode(0)), *cur(pre_head);

        while (p1 != NULL && p2 != NULL) {
            if (p1->val < p2->val) {
                cur->next = p1;
                p1 = p1->next;
            }
            else {
                cur->next = p2;
                p2 = p2->next;
            }
            cur = cur->next;
        }
        if (p1 != NULL) {
            cur->next = p1;
        }
        else if (p2 != NULL) {
            cur->next = p2;
        }

        ListNode *head = pre_head->next;
        pre_head->next = NULL;
        delete pre_head;
        return head;
    }
};

遞歸實現:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1 == NULL)
            return l2;
        if(l2 == NULL)
            return l1;

        if(l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章