手写了一个顺序表的操作,复习了一下c语言的相关知识;在操作指针时,一定要谨慎,特别是在结构体中,因为连续的地址,容易错误修改临近值,产生一个莫名其妙的bug;每次向系统malloc了资源,要还给人家,有借有还,再借不难;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <stdio.h> #include <windows.h> #define Listsize 10
struct Seqlist { int data[Listsize]; int length; };
void Initlist(struct Seqlist *L) { memset(L, 0, sizeof(int) * Listsize); L->length = 0; printf("Initlist success\n"); }
void Insert(struct Seqlist *L, int data, int index) { if (index < 0 || index > Listsize) { printf("error\n"); return; }
for (int i = L->length; i > index; i--) L->data[i + 1] = L->data[i]; L->data[index] = data; L->length++; }
void Delete(struct Seqlist *L, int index) { if (index < 0 || index > L->length) { printf("error\n"); return; }
for (int i = index; i < L->length - 1; i++) L->data[i] = L->data[i + 1]; L->data[L->length - 1] = 0; L->length--; }
int Get(struct Seqlist *L, int index) { if (index < 0 || index > L->length) { printf("error\n"); return 0; } return L->data[index]; }
void Destroy(struct Seqlist *L) { L->length = 0; free(L->data); printf("Destroy success\n"); }
void Print(struct Seqlist *L) { for (int i = 0; i < Listsize; i++) printf("%d ", L->data[i]); printf("L->length:%d ", L->length); printf("\n"); }
void main() { struct Seqlist *L; L = (struct Seqlist *)malloc(sizeof(struct Seqlist)); Initlist(L);
for (int i = 0; i < Listsize; i++) Insert(L, i, i); Print(L);
for (int i = 0; i < L->length; i++) Delete(L, i); Print(L);
for (int i = 0; i < L->length; i++) Get(L, i); Print(L);
Destroy(L); }
|
结果
1 2 3 4 5
| Initlist success 0 1 2 3 4 5 6 7 8 9 L->length:10 1 3 5 7 9 0 0 0 0 0 L->length:5 1 3 5 7 9 0 0 0 0 0 L->length:5 Destroy success
|