21. Merge Two Sorted Lists(easy)

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/86529327

Easy

1753240FavoriteShare

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

 

C++:

/*
 @Date    : 2019-01-08 11:01:14
 @Author  : 酸饺子 ([email protected])
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://leetcode.com/problems/merge-two-sorted-lists/
 */

/**
 * 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)
    {
        ListNode *l = new ListNode(0), *p = nullptr;
        l->next = nullptr;
        p = l;
        while (l1 && l2)
        {
            if (l1->val <= l2->val)
            {
                p->next = new ListNode(l1->val);
                l1 = l1->next;
            }
            else
            {
                p->next = new ListNode(l2->val);
                l2 = l2->next;
            }
            p = p->next;
        }
        while (l1)
        {
            p->next = new ListNode(l1->val);
            p = p->next;
            l1 = l1->next;
        }
        while (l2)
        {
            p->next = new ListNode(l2->val);
            p = p->next;
            l2 = l2->next;
        }
        ListNode* ret = l->next;
        delete l;
        return ret;
    }
};

Java:

/**
 * @Date    : 2019-01-08 11:17:21
 * @Author  : 酸饺子 ([email protected])
 * @Link    : https://github.com/SourDumplings
 * @Version : $Id$
 *
 * https://leetcode.com/problems/merge-two-sorted-lists/
*/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution
{
    public ListNode mergeTwoLists(ListNode l1, ListNode l2)
    {
        ListNode l = new ListNode(0), p = null;
        l.next = null;
        p = l;
        while (l1 != null && l2 != null)
        {
            if (l1.val <= l2.val)
            {
                p.next = new ListNode(l1.val);
                l1 = l1.next;
            }
            else
            {
                p.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            p = p.next;
        }
        while (l1 != null)
        {
            p.next = new ListNode(l1.val);
            p = p.next;
            l1 = l1.next;
        }
        while (l2 != null)
        {
            p.next = new ListNode(l2.val);
            p = p.next;
            l2 = l2.next;
        }
        return l.next;
    }
}

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/86529327
今日推荐