数据结构(C语言版)设有线性表LA(3,5,8,110)和LB(2,6,8,9,11,15,20)求新集合?

数据结构(C语言版)设有线性表LA(3,5,8,110)和LB(2,6,8,9,11,15,20)求新集合?
1:若LA和LB分别表示两个集合A和B,求新集合A=A∪B(相同元素不保留)预测输出LA=(3,5,8,11,2,6,9,15,20)
2:若LA和LB分别表示两个集合A和B,求新集合A=A∪B(相同元素保留)预测输出LA=(2,3,5,6,8,8,9,11,11,15,20)
数据结构(C语言版)设有线性表LA(3,5,8,11)和LB(2,6,8,9,11,15,20)求新集合
其他人气:553 ℃时间:2020-03-22 18:35:54
优质解答
#include
#include
#define list_init_size 100
#define listincrement 10
typedef struct
{ int *elem;
int length;
int listsize;
} sqlist;
int initsqlist (sqlist *l)//初始化
{
l->elem=(int *)malloc(list_init_size*sizeof(int));
\x09if(!l->elem)
\x09\x09exit(0);
\x09l->length=0;
\x09l->listsize=list_init_size;
\x09return 0;
}
int listinsert_sq(sqlist *l,int i,int e)//插入一个元素
{
\x09int *p,*q;
\x09if(il->length+1)
\x09\x09exit(0);
\x09q=&(l->elem[i-1]);
\x09for(p=&(l->elem[l->length-1]);p>=q;--p)
\x09\x09*(p+1)=*p;
\x09*q=e;
\x09++l->length;
\x09return 0;
}
void add(sqlist *l,int e)//添加到最后
{
listinsert_sq(l,l->length+1,e);
}
void disp(sqlist *l)
{
int i;
for(i=0;ilength;i++)
\x09 printf("%d ",l->elem[i]);
printf("\n");
}
int find(sqlist *l,int e)//查找元素是否存在
{
int i,t=-1;
for(i=0;ilength;i++)
\x09if(l->elem[i]==e)
\x09{t=i;break;}
return t;
}
void opt_1(sqlist *la,sqlist *lb)//(相同元素不保留)
{
int i,j;
for(i=0;ilength;i++)
{
\x09j = find(la,lb->elem[i]);
if(j==-1)
\x09\x09listinsert_sq(la,la->length+1,lb->elem[i]);
}
}
void sort(sqlist *la) //排序
{
\x09int i,j,k;
\x09for(i=0;ilength;i++)
\x09\x09for(j=i+1;jlength;j++)
\x09\x09{
\x09\x09 if(la->elem[i]>la->elem[j])
\x09\x09 {
\x09\x09\x09 k = la->elem[i];
\x09\x09\x09 la->elem[i] = la->elem[j];
\x09\x09\x09 la->elem[j] = k;
\x09\x09 }
\x09\x09}
}
void opt_2(sqlist *la,sqlist *lb)//(相同元素保留)
{
int i,j;
for(i=0;ilength;i++)
{
\x09j = find(la,lb->elem[i]);
if(j!=-1)
\x09\x09listinsert_sq(la,j+1,lb->elem[i]);
\x09else
\x09\x09listinsert_sq(la,la->length+1,lb->elem[i]);
}
sort(la);
}
int main()
{
\x09sqlist La,Lb;
\x09initsqlist(&La);
add(&La,3);
add(&La,5);
add(&La,8);
add(&La,11);
\x09initsqlist(&Lb);
add(&Lb,2);
add(&Lb,6);
add(&Lb,8);
add(&Lb,9);
add(&Lb,11);
add(&Lb,15);
add(&Lb,20);
\x09disp(&La);
\x09disp(&Lb);
\x09opt_1(&La,&Lb);//操作(相同元素不保留)
\x09disp(&La);
\x09La.length = 0; //重新初始化La
add(&La,3);
add(&La,5);
add(&La,8);
add(&La,11);
\x09opt_2(&La,&Lb);//操作(相同元素保留)
\x09disp(&La);
\x09
\x09return 0;
}
输出:
3 5 8 11
2 6 8 9 11 15 20
3 5 8 11 2 6 9 15 20
2 3 5 6 8 8 9 11 11 15 20
我来回答
类似推荐
请使用1024x768 IE6.0或更高版本浏览器浏览本站点,以保证最佳阅读效果。本页提供作业小助手,一起搜作业以及作业好帮手最新版!
版权所有 CopyRight © 2012-2024 作业小助手 All Rights Reserved. 手机版