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

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;
}
相关推荐
郝学胜-神的一滴9 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
玉梅小洋10 小时前
Windows 10 Android 构建配置指南
android·windows
不知名XL14 小时前
day50 单调栈
数据结构·算法·leetcode
cpp_250116 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250116 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder12317 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
雨中风华17 小时前
Linux, macOS系统实现远程目录访问(等同于windows平台xFsRedir软件的目录重定向)
linux·windows·macos
季明洵17 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi17 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_250117 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷