Leetcode(7)合并两个有序链表

题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解题思路
单项有序链表嘛,无非是指针的操作,两个有序链表,将其合并为一个有序链表,只需逐个判断其大小,然后操作指针即可

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *l = new ListNode(-1), *curent = l;
        while (l1 && l2) {
            if (l1->val < l2->val) 
            {
                curent->next = l1; l1 = l1->next;curent = curent->next;
            } else
             {
                curent->next = l2; l2 = l2->next;curent = curent->next;
            }
        }
        curent->next = l1 ? l1 : l2;
        return l->next;
    }
};

第二种解题思路
利用递归的方式,这个有点难,参考了下别人的代码

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43624053/article/details/84103132