首先建一个线性表
#include <bits/stdc++.h>
using namespace std;
#define LIST_INT_SIZE 100 //初始分配量
#define LIST_INCREMENT 10 //分配增量
typedef int ElemType; //元素数据类型
typedef struct
{
ElemType *elem; //存储空间基址
int lenth; //当前长度
int listsize; //当前分配的存储容量
}SqList;
//初始化线性表
int InitList_Sq(SqList &L)
{
L.elem = (ElemType*)malloc(LIST_INT_SIZE*sizeof(ElemType));
if(!L.elem) return 0;
L.lenth = 0;
L.listsize = LIST_INT_SIZE;
return 1;
}
//插入
int ListInsert_Sq(SqList &L, int i, ElemType e)
{
if(i<1 || i>L.lenth+1) return 0; //判断i是否有效
if(L.lenth>=L.listsize) //当前内存已满,重新增加
{
ElemType *newbase;
newbase = (ElemType*)realloc(L.elem,(L.listsize+LIST_INCREMENT)*sizeof(ElemType));
if(!newbase) return 0;
L.elem = newbase; //新基址
L.listsize += LIST_INCREMENT; //增内存容量
}
ElemType *p, *q;
q = &(L.elem[i-1]); //插入位置
for(p=&(L.elem[L.lenth-1]); p>=q; p--)
{
*(p+1) = *p;
}
*q = e;
L.lenth++;
return 1;
}
//输出
void dispList(SqList &L)
{
for(int i=0;i<L.lenth;i++)
{
printf("%d ",L.elem[i]);
}
cout<<endl;
}
//差集
void Diffence(SqList A,SqList B,SqList &C)
{ int i,j,k=0; //k记录C中的元素个数
for(i=0; i<A.lenth; i++) //遍历顺序表A
{ j=0;
while(j<B.lenth&&B.elem[j]!=A.elem[i])
j++;
if(j==B.lenth) //表示A.elem[i]不在B中,将其放到C中
C.elem[k++]=A.elem[i];
}
C.lenth=k; //修改集合长度
}
//交
void Intersection(SqList A,SqList B,SqList &C)
{ int i,j,k; //k记录C中的元素个数
for(i=0; i<A.lenth; i++) //用i遍历顺序表A
{ j=0;
while(j<B.lenth&&B.elem[j]!=A.elem[i])
j++;
if(j<B.lenth) //表示A.elem[i]在B中,将其放到C中
C.elem[k++]=A.elem[i];
}
C.lenth=k; //修改集合长度
}
//并
void Union(SqList A,SqList B,SqList &C)
{ int i,j,k; //k记录C中的元素个数
for(i=0; i<A.lenth; i++) //将A中元素复制到C中
C.elem[i]=A.elem[i];
k=A.lenth;
for(i=0; i<B.lenth; i++) //遍历顺序表B
{ j=0;
while(j<A.lenth&&B.elem[i]!=A.elem[j])
j++;
if(j==A.lenth) //表示B.elem[i]不在A中,将其放到C中
C.elem[k++]=B.elem[i];
}
C.lenth=k; //修改集合长度
}
差集:
A–>23 33 2 5 17 15 16 9
B–>33 5 16 28 9 10
遍历一遍A链表,i指向A中每一个数时,j遍历一遍B链表,若遍历中与i指的数相等,则结束,此时 j < B.lenth,i继续指向下一个数
否则完成一遍遍历j = B.lenth,说明i指向的数B中没有,此时,把A.elem[i]放进C链表中。
交集:
与上述思路差不多,j < B.lenth说明B中有与A中数相同的,放进C中
并集:
把A中所有元素放进C中,
剩下遍历方法和上同,改为遍历B,遍历A完后找不到B里面的元素,即
j = A.lenth,则把B.elem[i]放进C里面
总结:
j = B.lenth时,i指向的数只有A中有,不同
j < B.lenth时,i指向的数A,B中都有,相同