【leetcode 刷題日記】07-合併兩個有序鏈表(C++)

合併兩個有序鏈表

題目

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

思路

創建一個虛擬頭節點,用指針cur指向頭節點,然後和l1、l2比較,cur->next指向其中較小的一個。

/**
 * 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 && l2 == NULL)
            return NULL;
        ListNode* dummyHead = new ListNode(0);
        ListNode* cur = dummyHead;
        while(l1 != NULL || l2!= NULL){
            if(l1 == NULL || (l2 != NULL && (l1->val >= l2->val))){
                cur->next = l2;
                cur = cur->next;
                l2 = l2->next;
                continue;
            }
            if(l2 == NULL || (l1 != NULL && (l1->val < l2->val))){
                cur->next = l1;
                cur = cur->next;
                l1 = l1->next;
                continue;
            }
        }
        return dummyHead->next;
    }
};

C++
還有很簡潔優雅的遞歸思想,貼上來欣賞,我自己是想不到了

/**
 * 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;
    }
    }
};

但是遞歸的時間耗時好像更久一些。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章