一个C语言问题,急求!用带辅助表元的有序整数链表表示整数集合,分别编写已知两个集合求集合和(S1=S1∪S2)、集合差(S1=S1-S2)、集合交(S1=S1∩S2)的函数.运算结果在链表S1.设S1={2,3,5,6},S2=
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/06 05:12:14
一个C语言问题,急求!用带辅助表元的有序整数链表表示整数集合,分别编写已知两个集合求集合和(S1=S1∪S2)、集合差(S1=S1-S2)、集合交(S1=S1∩S2)的函数.运算结果在链表S1.设S1={2,3,5,6},S2=
一个C语言问题,急求!
用带辅助表元的有序整数链表表示整数集合,分别编写已知两个集合求集合和(S1=S1∪S2)、集合差(S1=S1-S2)、集合交(S1=S1∩S2)的函数.运算结果在链表S1.
设S1={2,3,5,6},S2={3,4,6,8}.谢谢!
一个C语言问题,急求!用带辅助表元的有序整数链表表示整数集合,分别编写已知两个集合求集合和(S1=S1∪S2)、集合差(S1=S1-S2)、集合交(S1=S1∩S2)的函数.运算结果在链表S1.设S1={2,3,5,6},S2=
#include "stdio.h"
#include "malloc.h"
typedef int datatype;
typedef struct Node{
datatype data;
Node *next;
}Set;
bool IsInSet(Set *set,datatype data) {
Node *p = set->next;
while(p){
if(p->data == data) return true;
p = p->next;
}
return false;
}
void InsertElem(Set *set,datatype data) {
Node *p = (Node *) malloc (sizeof(Node));
p->data = data;
p->next = set->next;
set->next = p;
}
void Union(Set *set1,Set *set2){ /*求并集*/
Node *p = set2->next;
while(p){
if(!IsInSet(set1,p->data)) InsertElem(set1,p->data);
p = p->next;
}
}
void Intersect(Set *set1,Set *set2) { /*求交集*/
Node *pre = set1,*cur = pre->next;
while(cur) {
if(!IsInSet(set2,cur->data)){
pre->next = cur->next;
free(cur);
}
else pre = cur;
cur = pre->next;
}
}
void Comple(Set *set1,Set *set2) { /*S1 = S1 - S2*/
Node *pre = set1,*cur = pre->next;
while(cur) {
if(IsInSet(set2,cur->data)) {
pre->next = cur->next;
free(cur);
}
else pre = cur;
cur = pre->next;
}
}
void CreateSet(Set *set,datatype endtag) {
Node *newNode;
datatype data;
scanf("%d",&data);
while(data != endtag) {
newNode = (Node*) malloc (sizeof(Node));
newNode->data = data;
newNode->next = set->next;
set->next = newNode;
scanf("%d",&data);
}
}
void ClearSet(Set *set) {
Node *p;
while(set->next) {
p = set->next;
set->next = p->next;
free(p);
}
}
void Display(Set *set) {
Node *p = set->next;
while(p) {
printf("%d\t",p->data);
p = p->next;
}
}
void main( ){
Set *set1,*set2,endtag;
set1 = (Node*) malloc (sizeof(Node));
set1->next = NULL;
set2 = (Node*) malloc (sizeof(Node));
set2->next = NULL;
printf("请设置链表输入结束标识:");
scanf("%d",&endtag);
CreateSet(set1,endtag);
CreateSet(set2,endtag);
Union(set1,set2);
Display(set1);
ClearSet(set1);
ClearSet(set2);
CreateSet(set1);
CreateSet(set2);
Intersect(set1,set2);(
Display(set1);
ClearSet(set1);
ClearSet(set2);
CreateSet(set1);
CreateSet(set2);
Comple(set1,set2);
Display(set1);
}