操作步骤:
1,求两个线性表的长度
2,从线性表LB中依次察看每个数据元素:GetElem(LB,i) -> e
3,依次在线性表LA中进行查仿:LocateElem(LA,e, equal())
4,若不存在,则插入之。ListInsert(LA,n+1, e)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define Capacity1 5 4 #define Capacity2 10 5 6 struct List { 7 int* ElemSet; 8 int len; 9 int capacity; 10 }list1,list2; 11 12 13 void initList() { 14 list1.len = 0,list2.len=0; //空表的长度初始化为0 15 list1.capacity = 5; //空表1的初始存储空间为5个int 16 list2.capacity = 10; //空表2的初始存储空间为10个int 17 list1.ElemSet = (int*)malloc(Capacity1 * sizeof(int)); //给list1申请5个int空间 18 list2.ElemSet = (int*)malloc(Capacity2 * sizeof(int)); //给list2申请10个int空间 19 if ((!list1.ElemSet) || (!list2.ElemSet)) { 20 printf("初始化失败 "); 21 return; 22 } 23 else { 24 printf("成功创建动态数组 "); 25 //给表1中初始化5个数据 26 for (int i = 0;i < 5;i++) { 27 list1.ElemSet[i] = i+1 ; //1 2 3 4 5 28 list1.len++; 29 } 30 //给表2中初始化7个数据 31 for (int i = 0;i < 7;i++) { 32 list2.ElemSet[i] = i + 3; // 3 4 5 6 7 8 9 33 list2.len++; 34 } 35 } 36 } 37 38 //打印表中所有数据 39 void showList(struct List list) { 40 for (int i = 0;i < list.len;i++) { 41 printf("%d ", list.ElemSet[i]); 42 } 43 printf(" "); 44 } 45 46 47 48 //顺序表查找元素 49 int searchElem(struct List list,int e) { 50 for (int i = 0;i < list.len;i++) { 51 if (list.ElemSet[i] == e) { 52 return i; 53 } 54 } 55 return -1; 56 } 57 58 59 //在表中插入元素 60 void insertElem(struct List list, int e, int insertIndex) { 61 62 for (int i = list.len - 1;i >= insertIndex;i--) { 63 list.ElemSet[i + 1] = list.ElemSet[i]; 64 //showList(list); 65 } 66 list.ElemSet[insertIndex] = e; 67 } 68 69 70 //list1和list2求并 71 void unionList(struct List list1, struct List list2) { 72 for (int i = 0;i < list1.len;i++) { 73 if (searchElem(list2, list1.ElemSet[i]) == -1) { 74 list2.len++; 75 insertElem(list2, list1.ElemSet[i], i); 76 } 77 } 78 showList(list2); 79 printf("表的长度是:%d ", list2.len); 80 } 81 82 void main() { 83 initList(); 84 printf("list1中的数据是:"); 85 showList(list1); 86 printf("list2中的数据是:"); 87 showList(list2); 88 printf("合并list1和list2后的表是:"); 89 unionList(list1, list2); 90 }