数据结构-线性表顺序结构(合并,删除,插入)
1 #include<stdio.h> 2 #include<stdlib.h> 3 int Max=100; 4 int add=10; 5 typedef struct { 6 int *elem; 7 int length; 8 int size; 9 }Sqlist; 10 11 int Create_list(Sqlist &L) { 12 L.elem = (int *)malloc(Max * sizeof(int)); 13 if (!L.elem) { 14 printf("顺序表构建失败\n"); 15 return 0; 16 } 17 L.length = 0; 18 L.size = 100; 19 printf("输入数据,输入-1结束\n"); 20 int i = 0; 21 int num=0; 22 while (num!=-1 && L.length!=100) { 23 scanf_s("%d", &num); 24 if (num != -1) { 25 L.elem[i] = num; 26 i++; 27 L.length++; 28 } 29 } 30 } 31 //插入 32 int Insert_list(Sqlist &L, int e) { 33 int i; 34 printf("请输入插入位置\n"); 35 scanf_s("%d", &i); 36 if (i<1 || i>L.length+1) { 37 printf("越界\n"); 38 return 0; 39 } 40 if (L.length >= L.size) { 41 int *newbase; 42 newbase= (int *)realloc(L.elem,(L.length + add)*sizeof(int)); 43 if (!newbase) { 44 printf("空间增加失败\n"); 45 return 0; 46 } 47 L.elem = newbase; 48 L.size += add; 49 } 50 for (int j = L.length; j >= i; j--) { 51 L.elem[j + 1] = L.elem[j]; 52 } 53 L.elem[i] = e; 54 L.length++; 55 } 56 //删除 57 int Delete_list(Sqlist &L, int e) { 58 int i = -1; 59 for (int j = 0; j < L.length; j++) { 60 if (L.elem[j] == e) { 61 i = j; 62 break; 63 } 64 } 65 if (i < 0) { 66 printf("表中不存在此数据\n"); 67 return 0; 68 } 69 for (int m = i + 1; m <L.length; m++) { 70 L.elem[m - 1] = L.elem[m]; 71 } 72 L.length--; 73 } 74 void travel_list(Sqlist &L) { 75 for (int i = 0; i < L.length; i++) { 76 printf("%d", L.elem[i]); 77 printf(" "); 78 } 79 printf("\n"); 80 } 81 //合并 82 int MergeList(Sqlist La, Sqlist Lb, Sqlist &Lc) { 83 Lc.elem = (int *)malloc((La.size + Lb.size) * sizeof(int)); 84 if (!Lc.elem) { 85 printf("内存空间分配失败\n"); 86 return 0; 87 } 88 Lc.length = 0; 89 Lc.size = La.size + Lb.size; 90 int pa = 0, pb = 0,pc=0; 91 while (pa < La.length && pb < Lb.length) { 92 if (La.elem[pa] > Lb.elem[pb]) { 93 Lc.elem[pc] = Lb.elem[pb]; 94 pc++; 95 pb++; 96 Lc.length++; 97 } 98 if (La.elem[pa] < Lb.elem[pb]) { 99 Lc.elem[pc] = La.elem[pa]; 100 pc++; 101 pa++; 102 Lc.length++; 103 } 104 if (La.elem[pa] == La.elem[pb]) { 105 Lc.elem[pc] = La.elem[pa]; 106 pa++; 107 pb++; 108 pc++; 109 Lc.length++; 110 } 111 } 112 if (pa >= La.length) { 113 while (pb < Lb.length) { 114 Lc.elem[pc] = Lb.elem[pb]; 115 pc++; 116 pb++; 117 Lc.length++; 118 } 119 } 120 if(pb>=Lb.length) { 121 while (pa < La.length) { 122 Lc.elem[pc] = La.elem[pa]; 123 pa++; 124 pc++; 125 Lc.length++; 126 } 127 } 128 } 129 int main() { 130 /*Sqlist L; 131 Create_list(L); 132 travel_list(L); 133 Insert_list(L, 8); 134 travel_list(L); 135 Delete_list(L, 1); 136 travel_list(L);*/ 137 Sqlist La; 138 Sqlist Lb; 139 Sqlist Lc; 140 Create_list(La); 141 Create_list(Lb); 142 MergeList(La, Lb, Lc); 143 travel_list(La); 144 travel_list(Lb); 145 travel_list(Lc); 146 return 0;
小白一枚,请多指教。

浙公网安备 33010602011771号