每日一练——求并集(C语言)

题目描述:

输出两个单向有序链表的并集
如链表 A {1 -> 2 -> 5 -> 7} 链表 B {3 -> 5 -> 7 -> 8} 输出: {1 -> 2 ->3 -> 5 -> 7 ->8} 。
(测试用例仅做参考,我们会根据代码质量进行评分)

输入描述:

第一行输入整数n,m,(1<=n,m<=1000)分别表示两个链表的长度。
第二行给出A链表所包含元素。(1<=a<=1000)
第三行给出B链表所包含元素。(1<=b<=1000)

实现方法很多,一般可以想到用数组来实现,但是可能通不过所有的测试用例,避免被ban还是用动态灵活的链表来实现吧!

100%通过代码如下:

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

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* mergeList(struct ListNode* l1, struct ListNode* l2){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); // 新建一个虚拟头节点
    dummy->val = 0;
    dummy->next = NULL;
    struct ListNode* cur = dummy;
    while (l1 && l2) {
        if (l1->val <= l2->val) {
            cur->next = l1;
            l1 = l1->next;
        } else {
            cur->next = l2;
            l2 = l2->next;
        }
        cur = cur->next;
    }
    if (l1) cur->next = l1; // 将剩余的节点加入到新链表中
    if (l2) cur->next = l2;
    return dummy->next;
}

int main() {
    int n, m, num;
    scanf("%d %d", &n, &m);
    struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p1 = l1;
    struct ListNode* p2 = l2;
    for (int i = 0; i < n; i++) {
        scanf("%d", &num);
        p1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        p1->next->val = num;
        p1->next->next = NULL;
        p1 = p1->next;
    }
    for (int i = 0; i < m; i++) {
        scanf("%d", &num);
        p2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        p2->next->val = num;
        p2->next->next = NULL;
        p2 = p2->next;
    }
    struct ListNode* res = mergeList(l1->next, l2->next);

    int hash[10001] = {0}; // 哈希表,假设节点值范围在 [0, 10000]
    struct ListNode* cur = res;
    struct ListNode* pre = NULL;
    while (cur) {
    if (hash[cur->val]) { // 如果当前节点值已经出现过,则删除当前节点
        pre->next = cur->next;
        free(cur);
        cur = pre->next;
    } else { // 如果当前节点值没有出现过,则将其加入哈希表,并继续遍历下一个节点
        hash[cur->val] = 1;
        pre = cur;
        cur = cur->next;
    }
}

    cur = res; 
    while (res) {

        printf("%d ", res->val);
        if(res->next!=NULL)
        {
            printf("-> ");
        }
        res = res->next;
    }
    cur = res;
    while (cur) 
    {
        struct ListNode* temp = cur;
        cur = cur->next;
        free(temp);
    }

return 0;
}

补充

  • 在创建链表后,使用了简单的归并排序(当然你可以使用更复杂性能更好的排序方法)
  • 最后用Hash表检测是否有元素重复,通过遍历赋值去重
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

炸弹气旋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值