/* 描述 已知集合A与集合B,且第个集合内数据是唯一的。求A,B集合合并成新的集合C,要求C集合内的数据也是唯一的。并指出C集合的个数。 输入 三行,第一行分别为集合A,B的个数 第二行为A集合的数据 第三行为B集合的数据 输出 两行 第一行集合C的个数 第二行为C集合的数据 样例输入 */ #include <iostream> using namespace std; bool flag[30000]; int pos = 1; template <typename T> struct Node { T data; Node<T> *next; }; template <typename T> class List { private: Node<T> *first; int length; public: List(); bool ListInsert(Node<T> *N, int i, int data); void MegList(List<T> *List); List(int size); void display(); ~List(); }; template <typename T> List<T>::List() { first = new Node<T>; first->next = nullptr; } template <typename T> List<T>::~List() { Node<T> *q; while (first) { q = first->next; delete first; first = q; } } template <typename T> List<T>::List(int size) { first = new Node<T>; first->next = nullptr; int temp = 0; for (int i = 1; i <= size; i++) { cin >> temp; ListInsert(first, i, temp); } } template <typename T> bool List<T>::ListInsert(Node<T> *N, int i, int data) { Node<T> *p = new Node<T>; p = N; int j = 0; while (p && j < i - 1) { p = p->next; j++; } if (!p || j > i - 1) { return 0; } Node<T> *s = new Node<T>; s->data = data; s->next = p->next; p->next = s; return 1; } template <typename T> void List<T>::MegList(List<T> *List) { Node<T> *p = new Node<T>; p = List->first->next; while (p) { int tempdata = p->data; if (flag[tempdata] == 0) { ListInsert(first, pos, tempdata); flag[tempdata] = 1; p = p->next; pos++; } else { p = p->next; } } length = pos - 1; } template <typename T> void List<T>::display() { cout << length << endl; Node<T> *p = new Node<T>; p = first->next; while (p != nullptr) { cout << p->data << " "; p = p->next; } } int work() { int n, m; cin >> n >> m; List<int> *list1 = new List<int>(n); List<int> *list2 = new List<int>(m); List<int> *list3 = new List<int>; list3->MegList(list1); list3->MegList(list2); list3->display(); return 1; } int main() { work(); system("pause"); return 0; }
数据结构-线性表-集合合并新思路
最新推荐文章于 2023-08-08 21:02:25 发布