LeetCode 21 合并两个有序链表

21. 合并两个有序链表

难度简单2394收藏分享切换为英文接收动态反馈

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

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1 和 l2 均按 非递减顺序 排列

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* ret = newnode;
    while(list1 && list2){
        if(list1 -> val < list2 -> val){
            newnode -> next = list1;
            list1 = list1 -> next;
        }
        else{
            newnode -> next = list2;
            list2 = list2 -> next;
        }
        newnode = newnode -> next;
    }
    if(list2){
        newnode -> next = list2;
    }
    else{
        newnode -> next = list1;
    }
    //newnode -> next = list1 == NULL ? list2 : list1;
    return ret -> next;
}

记录一下对这个题的最基层的理解:首先有一点是,其实这个题里的newnode list1 list2等等都是节点(结构体)的指针,每当传递他们时,都是传的对应节点的地址,而使用newnode->xx list1->xx list2->xx 时也都是通过这个节点的地址去访问对应的内存区域(里面存储着一个数据,和另一个节点的地址)。

所以,创建一个新的节点,将这个节点的next作为返回值,每次比较list1和list2对应值的大小,将较小者的地址,即list1或list2本身传递给newnode的next,然后将他们本身改为他们的next。临时加一个例子吧:链表1为1 3 5 链表2为 2 4 6 则传递1的地址作为newnode的next之后,将list1改为data为3的那个节点的地址,然后比较3和2。此时2较小,则newnode->next改为data为2的那个节点的地址。其实这里newnode就是data为1的那个节点的地址,此时改了之后,1就会指向2。而这里不会出现错误的原因是,在1指向2之前,list1已经改为list1的next了。 

over 

递归版本

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    if(list1 == NULL)
        return list2;
    if(list2 == NULL)
        return list1;
    if(list1 -> val < list2 -> val)
    {
        list1 -> next = mergeTwoLists(list1 -> next, list2);
        return list1;
    }
    else 
    {
        list2 -> next = mergeTwoLists(list1, list2 -> next);
        return list2;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值