【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;
    }
    }
};

但是递归的时间耗时好像更久一些。

发布了7 篇原创文章 · 获赞 4 · 访问量 127

猜你喜欢

转载自blog.csdn.net/fengshiyu1997/article/details/104716347