求序列的交集(链表)
时间限制: 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;
}