【东华大学oj】求序列的交集(链表)

求序列的交集(链表)

时间限制: 1s

类别: DS:数组与链表->链表--简单

问题描述

使用带头结点的单链表编程:

有两个序列,分别表示两个集合。

求它们的交集并输出。

输入说明

第一行输入序列A的信息:

第一个整数n(0<=n<=100),表示共有n个元素,其后有n个整数,表示n个元素的数据

第一行输入序列B的信息:

第一个整数n(0<=n<=100),表示共有n个元素,其后有n个整数,表示n个元素的数据

输出说明

输出交集的元素序列,输出格式见范例。

如果交集为空,则输出“head-->tail”

交集里的元素顺序,依照其在序列A中的顺序。

比如:

序列:

A:5 3 2 7

B:1 3 5 8

则交集为5和3,因为在序列A中,5在3的前面,所以在交集里5也在3的前面。

#include <iostream>
using namespace std;

// 定义链表节点结构体
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

// 添加元素到链表
void addToList(ListNode* &head, int val) {
    ListNode *newNode = new ListNode(val);
    if (!head) {
        head = newNode;
    } else {
        ListNode *temp = head;
        while (temp->next) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}

// 创建链表
ListNode* createList(int n) {
    ListNode *head = nullptr;
    int val;
    for (int i = 0; i < n; ++i) {
        cin >> val;
        addToList(head, val);
    }
    return head;
}

// 检查链表中是否包含特定值
bool contains(ListNode* head, int val) {
    ListNode *temp = head;
    while (temp) {
        if (temp->val == val) return true;
        temp = temp->next;
    }
    return false;
}

// 计算两个链表的交集
ListNode* intersection(ListNode* list1, ListNode* list2) {
    ListNode *resultHead = nullptr;
    ListNode *temp = list1;
    while (temp) {
        if (contains(list2, temp->val)) {
            addToList(resultHead, temp->val);
        }
        temp = temp->next;
    }
    return resultHead;
}

// 打印链表
void printList(ListNode* head) {
    if (!head) {
        cout << "head-->tail" << endl;
        return;
    }
    cout << "head";
    while (head) {
        cout << "-->" << head->val;
        head = head->next;
    }
    cout << "-->tail" << endl;
}

int main() {
    int n;
    
    // 读取序列A
    cin >> n;
    ListNode *listA = createList(n);
    
    // 读取序列B
    cin >> n;
    ListNode *listB = createList(n);
    
    // 计算交集
    ListNode *intersectionList = intersection(listA, listB);
    
    // 打印交集
    printList(intersectionList);
    
    return 0;
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ixll625

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

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

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

打赏作者

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

抵扣说明:

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

余额充值