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

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;
}
相关推荐
丶Darling.23 分钟前
26考研 | 王道 | 数据结构 | 第七章 查找
前端·数据结构·考研
刃神太酷啦24 分钟前
堆和二叉树--数据结构初阶(3)(C/C++)
c语言·数据结构·c++·算法·leetcode·深度优先·宽度优先
良木林1 小时前
240424 leetcode exercises II
c语言·数据结构·算法·leetcode
啊阿狸不会拉杆1 小时前
数据结构-排序
java·c语言·数据结构·c++·python·算法·排序算法
姜行运1 小时前
数据结构【树和二叉树】
android·数据结构·算法·c#
xin007hoyo3 小时前
算法笔记.spfa算法(bellman-ford算法的改进)
数据结构·笔记·算法
老兵发新帖3 小时前
pnpm install报错:此系统上禁止运行脚本
windows
新生农民4 小时前
30分钟解决8道算法题
java·数据结构·算法
bbc1212264 小时前
2025/4/23 心得
数据结构·算法
zhishishe5 小时前
2025 年免费 Word 转 PDF 转换器有哪些?
android·windows·pdf·电脑·word