【力扣 简单 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);
}
相关推荐
songx_9913 分钟前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
Yuki’18 分钟前
网络编程---UDP
c语言·网络·网络协议·udp
鲸屿19521 分钟前
python之socket网络编程
开发语言·网络·python
没有梦想的咸鱼185-1037-16631 小时前
基于R语言机器学习方法在生态经济学领域中的实践技术应用
开发语言·机器学习·数据分析·r语言
.YM.Z1 小时前
C语言——文件操作
c语言·文件操作
先做个垃圾出来………1 小时前
差分数组(Difference Array)
java·数据结构·算法
向上的车轮1 小时前
基于go语言的云原生TodoList Demo 项目,验证云原生核心特性
开发语言·云原生·golang
The Chosen One9851 小时前
C++ : AVL树-详解
开发语言·c++
PH_modest1 小时前
【Qt跬步积累】—— 初识Qt
开发语言·qt
hansang_IR2 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积