将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍使用原来两个链表的存储空间,不另外占用其他的存储空间。表中不允许有重复的数据。

#include <stdio.h>
#include <stdlib.h>

/* 定义链表节点结构体 */
struct ListNode {
    int val;
    struct ListNode* next;
};

/* 合并两个递增有序链表 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    /* 如果其中一个链表为空,则直接返回另一个链表 */
    if (!l1) {
        return l2;
    }
    if (!l2) {
        return l1;
    }

    /* 定义指针 p 和 q 分别指向两个链表的头结点 */
    struct ListNode* p = l1, * q = l2;

    /* 定义结果链表的头结点和尾结点 */
    struct ListNode* head = NULL, * tail = NULL;

    /* 比较两个链表中节点的大小,并将较小的节点加入结果链表中 */
    while (p && q) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        if (p->val < q->val) {
            node->val = p->val;
            p = p->next;
        }
        else {
            node->val = q->val;
            q = q->next;
        }
        if (!head) {
            head = tail = node;
        }
        else {
            tail->next = node;
            tail = tail->next;
        }
    }

    /* 将剩余的节点加入结果链表中 */
    if (p) {
        tail->next = p;
    }
    if (q) {
        tail->next = q;
    }

    return head;
}

/* 从键盘输入链表 */
struct ListNode* inputList() {
    int n;
    scanf_s("%d", &n);
    if (n == 0) {
        return NULL;
    }
    struct ListNode* head = NULL, * tail = NULL;
    for (int i = 0; i < n; i++) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        scanf_s("%d", &node->val);
        node->next = NULL;
        if (!head) {
            head = tail = node;
        }
        else {
            tail->next = node;
            tail = tail->next;
        }
    }
    return head;
}

/* 输出链表 */
void printList(struct ListNode* head) {
    while (head) {
        printf("%d ", head->val);
        head = head->next;
    }
    printf("\n");
}

int main() {
    /* 从键盘输入两个链表 */
    printf("请输入第一个链表的节点数:");
    struct ListNode* l1 = inputList();
    printf("请输入第二个链表的节点数:");
    struct ListNode* l2 = inputList();

    /* 合并两个链表 */
    struct ListNode* result = mergeTwoLists(l1, l2);

    /* 输出结果链表 */
    printf("合并后的链表为:");
    printList(result);

    return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值