【数据结构】【链表代码】合并有序链表

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 typedef struct ListNode Node;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    if(l1==NULL)
        return l2;
    if(l2==NULL)
        return l1;   
    //取小的尾插
    Node*head=NULL,*tail=NULL;
    if(l1->val<l2->val){
        head=tail=l1;
        l1=l1->next;
    }else{
        head=tail=l2;
        l2=l2->next;

    }

    while(l1&&l2){
        if(l1->val<l2->val){
            tail->next=l1;
            l1=l1->next;
        }else{
            tail->next=l2;
            l2=l2->next;
        }
        tail=tail->next;
    }

    if(l1)
        tail->next=l1;
    else
        tail->next=l2;
    return head;
}
相关推荐
_Itachi__19 分钟前
LeetCode 热题 100 160. 相交链表
算法·leetcode·链表
a小胡哦20 分钟前
Windows、Mac、Linux,到底该怎么选?
linux·windows·macos·操作系统
冠位观测者23 分钟前
【Leetcode 每日一题 - 扩展】1512. 好数对的数目
数据结构·算法·leetcode
_Itachi__25 分钟前
LeetCode 热题 100 560. 和为 K 的子数组
数据结构·算法·leetcode
进击的_鹏30 分钟前
【C++】list 链表的使用+模拟实现
开发语言·c++·链表
大模型铲屎官1 小时前
哈希表入门到精通:从原理到 Python 实现全解析
开发语言·数据结构·python·算法·哈希算法·哈希表
L_09071 小时前
【C】队列与栈的相互转换
c语言·开发语言·数据结构
苍老流年2 小时前
Redis底层数据结构
数据结构·数据库·redis
水月梦镜花2 小时前
数据结构:基数排序(c++实现)
开发语言·数据结构·c++
愈谦卑3 小时前
数据结构:排序
数据结构·算法·排序算法