Skip to content

21. 合并两个有序链表 #13

@MyLinChi

Description

@MyLinChi

题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方案

新链表采用尾插法,如果l1的元素小于l2的元素,则取l1的元素,否则取l2的元素。后面把剩下的元素连接到新链表的尾部。

/**
 * 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 t(0);
        ListNode* dummy = &t;
        ListNode* last = dummy;
        while(l1&&l2){
            if(l1->val<l2->val){
                last->next = l1;
                last = last->next;
                l1=l1->next;
            }else{
                last->next = l2;
                last = last -> next;
                l2 = l2->next;
            }
        }
        if(l1)
            last->next = l1;
        else
            last->next = l2;
        return
    }
};

方案二(递归)

合并连个链表的过程可以看做是先确定当前一个元素a,然后对剩下的元素进行合并,最后两个连接起来。

/**
 * 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;
        }
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions