【力扣 简单 C】21. 合并两个有序链表

目录

题目

解法一:迭代

解法二:递归


题目

解法一:迭代

cpp 复制代码
struct ListNode* merge(struct ListNode* head1, struct ListNode* head2)
{
    struct ListNode* virHead = malloc(sizeof(*virHead));
    struct ListNode* preNode = virHead;
    while (head1 && head2)
    {
        if (head1->val < head2->val)
        {
            preNode->next = head1;
            head1 = head1->next;
        }
        else
        {
            preNode->next = head2;
            head2 = head2->next;
        }
        preNode = preNode->next;
    }
    preNode->next = head1 ? head1 : head2;
 
    struct ListNode* retHead = virHead->next;
    free(virHead);
    return retHead;
}
 
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    return merge(list1, list2);
}

解法二:递归

cpp 复制代码
void swap(struct ListNode** a, struct ListNode** b)
{
    struct ListNode* tmp = *a;
    *a = *b;
    *b = tmp;
}

struct ListNode* merge(struct ListNode* head1, struct ListNode* head2)
{
    if (!head1)
        return head2;

    if (!head2)
        return head1;

    if (head1->val > head2->val)
        swap(&head1, &head2);

    head1->next = merge(head1->next, head2);
    return head1;
}

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    return merge(list1, list2);
}
相关推荐
夏日听雨眠16 小时前
数据结构(栈和队列)
数据结构
Aaswk16 小时前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite17 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
Cyber4K18 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
梦梦代码精18 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
Le_ee18 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
Zephyr_018 小时前
Leedcode算法题
java·算法
流年如夢19 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
yong999019 小时前
MATLAB读取高光谱图像
开发语言·matlab