题目:
集合A:1 3 5 7 //顺序表A
集合B:5 7 9 11 //顺序表B
求AUB:1 3 5 7 9 11
代码:
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct seqlist
{
int data[N];
int last;
} seqlist_t, *seqlist_p;
//创空
seqlist_p chuangkong()
{
seqlist_p p = (seqlist_p)malloc(sizeof(seqlist_t));
if (NULL == p)
{
perror("malloc err");
return NULL;
}
p->last = -1;
return p;
}
//并集函数
void bingji(seqlist_p p, seqlist_p q, seqlist_p k)
{
int i = 0, j = 0, n = 0;
//A,C中各拿出一个数比较大小,选出最小的
//然后去跟C中数字比较是否相同,不同就存入C中
while (i <= p->last && j <= q->last)
{
if (p->data[i] == q->data[j])
{
j++;
}
if (p->data[i] < q->data[j])
{
k->data[n++] = p->data[i++];
}
else
{
k->data[n++] = q->data[j++];
}
}
while (i <= p->last)
{
k->data[n++] = p->data[i++];
}
while (j <= q->last)
{
k->data[n++] = q->data[j++];
}
k->last = n -1;
}
//遍历
void bianli(seqlist_p p)
{
for (int i = 0; i <= p->last; i++)
printf("%d ", p->data[i]);
printf("\n");
}
int main(int argc, char const *argv[])
{
//集合A
struct seqlist A = {{1, 3, 5, 7}, 3};
seqlist_p p = &A;
printf("顺序表A为:\n");
bianli(p);
//集合B
struct seqlist B = {{5, 7, 9, 11}, 3};
seqlist_p q = &B;
printf("顺序表B为:\n");
bianli(q);
//集合C:AUB
seqlist_p c = chuangkong();
bingji(p, q, c);
printf("顺序表C为:\n");
bianli(c);
return 0;