Train of thought:
Don't think about deleting words, think about how to save non-x values
Two solutions are provided here, which have the same way:
1. Count and save the non-x elements
2. Count the number of elements x, and save the non-x elements
matters needing attention:
Note that due to the use of reference (&), the code here can only be compiled in C + +
When using the pointer, be sure to open up space, or you may find unpredictable errors later
The code is as follows:
Tap the plus sign and the code will appear1 #include <stdio.h> 2 #include <stdlib.h> 3 #define MaxSize 50 4 typedef int ElemType; 5 6 typedef struct { 7 ElemType data[MaxSize]; 8 int length; 9 } Sqlist; 10 11 //Which will not be x Element statistics and save 12 void delnode1(Sqlist* &L, ElemType x) { 13 int k = 0, i; 14 for(i = 0; i < L -> length; i++) { 15 if(L -> data[i] != x) { 16 L -> data[k] = L -> data[i]; 17 k++; 18 } 19 } 20 L -> length = k; 21 } 22 23 //Statistics for x The number of elements of the x Element save for 24 void delnode2(Sqlist* &L, ElemType x) { 25 int k = 0, i; 26 for (i = 0; i < L -> length; i++) { 27 if (L -> data[i] == x) { 28 k++; 29 } else { 30 L -> data[i - k] = L -> data[i]; 31 } 32 } 33 L -> length -= k; 34 } 35 36 void createList(Sqlist* &L, ElemType a[], int n) { 37 int i; 38 L = (Sqlist *)malloc(sizeof(Sqlist)); 39 for (i = 0; i < n; i++) { 40 L -> data[i] = a[i]; 41 } 42 L -> length = n; 43 } 44 45 void dispList(Sqlist *L) { 46 int i; 47 for (i = 0; i < L -> length; i++) { 48 printf("%d ", L -> data[i]); 49 } 50 printf("\n"); 51 } 52 53 int main(int argc, char const *argv[]) { 54 Sqlist *L; 55 ElemType a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 56 createList(L, a, 10); 57 printf("Original linear table:\n"); 58 dispList(L); 59 delnode1(L, 3); 60 printf("After deleting 3:\n"); 61 dispList(L); 62 delnode2(L, 4); 63 printf("After deleting 4:\n"); 64 dispList(L); 65 return 0; 66 }