//返回表长 intListLength(List L){ int cnt = 0; List p = L; while (p) { cnt++; p = p->Next; } return cnt; }
//返回元素的值 intGetElem(List L, ElementType pos){ List p = L; for (int i = 0; i < pos - 1; i++) p = p->Next; return p->data; }
//查找表中是否有对应元素 boolLocateElem(List L, ElementType v){ List p = L; while (p) { if (p->data == v) returntrue; p = p->Next; } returnfalse; }
//链表插入 voidListInsert(List L, ElementType pos, ElementType v){ List p = L; for (int i = 1; i < pos - 1; i++) p = p->Next; List temp = (List)malloc(sizeof(ListNode)); temp->data = v; temp->Next = p->Next; p->Next = temp; }
//链表打印及去重排序 voidPrintList(List L){ set<int> s; bool flag = false; List p = L; while (p) { printf("%s%d", flag ? " " : "", p->data); flag = true; p = p->Next; } cout << endl; p = L; flag = false; printf("去重后的元素:"); while (p) { s.insert(p->data); p = p->Next; } for (set<int>::iterator it = s.begin(); it != s.end(); it++) { printf("%s%d", flag ? " " : "", *it); flag = true; } cout << endl; p = L; flag = false; printf("排序后的元素为:"); for (auto it : s) { printf("%s%d", flag ? " " : "", it); flag = true; } cout << endl; }
voidPrintList2(List L){ bool flag = false; List p = L; while (p) { printf("%s%d", flag ? " " : "", p->data); flag = true; p = p->Next; } cout << endl; }
//链表创建 List create(char id){ ElementType all; printf("请输入集合%c的元素个数:%c = ", id, id + 23); scanf("%d", &all); printf("请输入集合%c的元素:", id); List head, p;//头插法创建链表 head = NULL; p = head; for (int i = 0; i < all; i++) { int n; cin >> n; p = (List)malloc(sizeof(struct ListNode)); p->data = n; p->Next = head; head = p; } printf("集合%c中的元素为:", id); PrintList(head); return head; }
//这个求并集的算法还是有些问题,待我日后再改。 voidUnionList(List a, List b){ int lena = ListLength(a), lenb = ListLength(b); for (int i = 1; i <= lenb; i++) { ElementType v = GetElem(b, i); if (!LocateElem(a, v)) ListInsert(a, ++lena, v); } printf("合并后的集合为:"); PrintList2(a);
}
intmain(){ List La = create('A'); List Lb = create('B'); UnionList(La, Lb); system("pause"); return0; }