考察的知识点:与链表有关的题基本都是插入,删除,交换顺序等,解决这些问题通常将链表的指针进行修改。

题目分析:这道题就是合并两个有序单链表,首先判断l1,l2是否有空,1. 若都为空,则返回空;2. 若一个为空,另一个不为空,则返回不为空的一个;3. 两个都不为空,开始遍历两个链表,比较两个结点的大小,插入大的那一个结点,若遍历某个链表为空,则将不为空的链表进行插入,否则继续遍历。

本题解析所用的编程语言:c++

ListNode* mergeEnergyValues(ListNode* l1, ListNode* l2)
{
    // write code here
    ListNode* head, * cur;
    //先判断是否有空
    if (l1 == nullptr && l2 != nullptr)
        return l2;
    else if (l1 != nullptr && l2 == nullptr)
        return l1;
    else if (l1 == nullptr && l2 == nullptr)
        return nullptr;

    //给head附头
    if (l1->val >= l2->val)
    {
        head = cur = l1;
        l1 = l1->next;
    }
    else
    {
        head = cur = l2;
        l2 = l2->next;
    }
    while (l1 || l2)//两个都空结束
    {
        //判断遍历时是否有空
        if (l1 == nullptr && l2 != nullptr)
        {
            cur->next = l2;
            return head;
        }
        else if (l1 != nullptr && l2 == nullptr)
        {
            cur->next = l1;
            return head;
        }
        if (l1->val >= l2->val)
        {
            cur->next = l1;
            cur = cur->next;
            l1 = l1->next;
        }
        else
        {
            cur->next = l2;
            cur = cur->next;
            l2 = l2->next;
        }
    }
    cur->next = nullptr;
    return head;
}