1 //删除线性表中不为x的元素。 2 void delete_list(Sqlist &L,int x){ 3 int k = 0; 4 for(int i=0;i < L.length;i++){ 5 if(L.data[i] != x){ 6 L.data[k] = L.data[i]; 7 k++; 8 } 9 } 10 L.length = k; 11 } 12 13 //先统计不为x的个数,然后将线性表中不为x的数据向前移动K个。 14 void delete_list(Sqlist &L,int x){ 15 int k = 0,i=0; 16 while(i < L.length){ 17 if(L.data[i] == x){ 18 k++; 19 } 20 else{ 21 L.data[i-k] = L.data[i]; 22 } 23 i++; 24 } 25 L.length = L.length - k; 26 } 27 28 //用头指针和尾指针同时向中间靠拢来实现。 29 void delete_list(Sqlist &L,int x){ 30 int k = 0,temp =0;int *head = L.data[0],*nail = L.data[L.length-1]; 31 while(head != nail){ 32 if(*head == x){ 33 while(*nail == x){ 34 nail--; 35 } 36 temp = *head; 37 *head = *nail; 38 *nail = temp; 39 } 40 else{ 41 head++; 42 } 43 44 } 45 }
时间: 2024-11-10 13:15:30