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

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;
}
相关推荐
阿白的白日梦1 天前
winget基础管理---更新/修改源为国内源
windows
埃博拉酱5 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21886 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号36 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
tryCbest6 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅6 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技6 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~6 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#