【剑指25】合并两个排序的链表

方法一:重新拼接两个链表:时间O(mn),空间O(1)

题解:

  1. 建立头结点
  2. 将两个链表按大小顺序拼接到头结点之后
  3. 循环结束,将剩下的一节拼接到后面
/**
 * 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) 
    {
    
    
        // 1.把一个链表插入另一个链表里
        ListNode* head = new ListNode(0);
        ListNode* cur = head;
        while (l1 && l2)
        {
    
    
            if (l1->val < l2->val)
            {
    
    
                cur->next = l1;
                l1 = l1->next;
            }
            else 
            {
    
    
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1 == nullptr ? l2 : l1;
        return head->next;
    }
};

方法二:递归(不创建头结点):时间O(mn),空间O(m) m>n

题解:

  1. 结束条件:两个链表其中一个为空
  2. 创建一个结点指向当前较小的值,该节点的 next 指向递归的下一个节点
  3. 返回节点
/**
 * 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) 
    {
    
    
        // 1.递归处理:不创建头结点
        if (l1 == nullptr)
            return l2;
        else if (l2 == nullptr)
            return l1;
        ListNode* head = nullptr;
        if (l1->val < l2->val)
        {
    
    
            head = l1;
            head->next = mergeTwoLists(l1->next, l2);
        }
        else 
        {
    
    
            head = l2;
            head->next = mergeTwoLists(l1, l2->next);
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/113852051