【LeetCode系列】21 Merge Two Sorted Lists 合并两个有序链表

题目描述:LeetCode原题地址
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.
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

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

解法一: 用最直接的思路,将两个链表l1l2直接从头到尾比较。即两个链表开始都指向头结点,进行比较,如果l1 -> val <= l2 -> val,则将l1的这个结点链接到新链表中,再使l1指向下一个结点继续比较;同理如果l1 -> val > l2 -> val,则将l2的结点放到新链表中,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 *merge = new ListNode(0);
        ListNode *head = merge;
        //当l1和l2都不为空时继续合并
        while(l1 && l2){
            //l1指向的结点值小于l2指向的结点值时,将l1拼接到merge后,l1指向下一个结点
            if(l1 -> val <= l2 -> val){
                head -> next = l1;
                l1 = l1 -> next;
            }else{  //否则(即l2的结点值小于l1),将l2拼接到merge后,l2指向下一个结点
                head ->next = l2;
                l2 = l2 -> next;
            }
            head = head -> next;
        }
        
        //l1或l2已经遍历完时,将未遍历完的直接拼接到merge链表的结尾
        head -> next = l1 ? l1 : l2;
        return merge -> next;
    }
};

解法二:LeetCode评论中看到的用递归实现的方法,觉得很惊艳,学习一下,以下代码来源于评论区。

代码二:

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(l2->next, l1);
            return l2;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值