问题描述:三个递增有序线性表A,B,C. 对A有这样操作:删除既在B中又在C中出现的元素,分别对顺序表和单链表编写实现上述操作的算法,并分析时间复杂度。
问题分析:此题的关键是对三个表中的元素进行比较,当A中有既在B中又在C中的元素时删除此元素。要这样比较,想到需要三个if嵌套,试着分析一下
我的分析貌似有道理,用三个嵌套,答案是结合上面的题,做了个综合运用,莫非这就是综合概况能力呢?真的很奇妙呀。
用顺序表实现的代码如下:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define LIST_INIT_SIZE 100 4 #define LISTINCREMENT 10 5 typedef struct{ 6 int *elem;//基址 7 int length;//表的长度 8 int listsize;//表的当前长度 9 }SqList;//结构体类型 10 void InitList_Sq(SqList &L) 11 { 12 L.elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int)); 13 if(!L.elem) 14 exit(0); 15 L.length=0; 16 L.listsize=LIST_INIT_SIZE; 17 } 18 void ListInsert_Sq(SqList &L,int i,int e) 19 { 20 //在顺序线性表L中第i个位置之前插入新的元素e 21 //i的合法值为1-L.length+1 22 if(i<1||i>L.length+1) 23 { 24 printf("插入的位置有误!"); 25 exit(0); 26 } 27 if(L.length>=L.listsize) 28 { 29 int *newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int)); 30 if(!newbase) 31 exit(0); 32 L.elem=newbase; 33 L.listsize+=LISTINCREMENT; 34 } 35 int *q=&(L.elem[i-1]); 36 *q=e; 37 L.length++; 38 } 39 void ListCross_LRS(SqList &B,SqList &C) 40 { 41 int i=0,j=0,k=0; 42 while(i<B.length&&j<C.length) 43 { 44 if(B.elem[i]<C.elem[j]) 45 i++; 46 else 47 { 48 if(B.elem[i]>C.elem[j]) 49 j++; 50 else 51 { 52 if(k==0) 53 { 54 B.elem[k]=B.elem[i]; 55 k++; 56 } 57 else//消除元素相同的 58 if(B.elem[k-1]!=B.elem[i]) 59 { 60 B.elem[k]=B.elem[i]; 61 k++; 62 } 63 i++; 64 j++; 65 } 66 }//end else 67 }//end while 68 B.length=k; 69 } 70 void ListCrossDelSame_L(SqList &A,SqList &B) 71 { 72 int i=0,j=0,k=0; 73 while(i<A.length&&j<B.length) 74 { 75 if(A.elem[i]<B.elem[j]) 76 { 77 A.elem[k++]=A.elem[i]; 78 i++; 79 } 80 else 81 { 82 if(A.elem[i]>B.elem[j]) 83 j++; 84 else 85 i++; 86 } 87 } 88 while(i<A.length) 89 { 90 A.elem[k++]=A.elem[i]; 91 i++; 92 } 93 A.length=k; 94 } 95 void ListCross_Sq(SqList &A,SqList &B,SqList &C) 96 { 97 ListCross_LRS(B,C); 98 ListCrossDelSame_L(A,B); 99 } 100 101 int main() 102 {//代码还是要规范点好,现在处于打基础阶段。。。。 103 SqList A,B,C; 104 int len_A,len_B,len_C,temp,i; 105 InitList_Sq(A); 106 printf("输入A表的长度:\n"); 107 scanf("%d",&len_A); 108 printf("将对应值值插入A表中:\n"); 109 for(i=1;i<=len_A;i++) 110 { 111 scanf("%d",&temp); 112 ListInsert_Sq(A,i,temp); 113 } 114 115 InitList_Sq(B); 116 printf("输入B表的长度:\n"); 117 scanf("%d",&len_B); 118 printf("将对应值值插入B表中:\n"); 119 for(i=1;i<=len_B;i++) 120 { 121 scanf("%d",&temp); 122 ListInsert_Sq(B,i,temp); 123 } 124 125 InitList_Sq(C); 126 printf("输入C表的长度:\n"); 127 scanf("%d",&len_C); 128 printf("将对应值值插入C表中:\n"); 129 for(i=1;i<=len_C;i++) 130 { 131 scanf("%d",&temp); 132 ListInsert_Sq(C,i,temp); 133 } 134 135 ListCross_Sq(A,B,C); 136 printf("对A表进行操作,删除既在B又在C中的元素后的值为:\n"); 137 for(i=0;i<A.length;i++) 138 printf("%d",A.elem[i]); 139 }