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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include <stdio.h> #include "malloc.h" #define MAX 100 #define increment_size 10
typedef struct DynSqeList{ int* elem; int length; int max; }DynSqeList;
void init(DynSqeList& L) { L.elem = (int*)malloc(sizeof(int) * 100); for (int i = 0; i < 10; i++) { L.elem[i] = i; L.length++; } }
void insert(DynSqeList& L, int index, int value) { if (index<0 || index >L.length) { printf("插入索引值超过边界"); return; } if (L.length == L.max) { int* NewArrayBase = (int*)realloc(L.elem, sizeof(int) * (L.length + increment_size)); for (int i = 0; i < L.length; i++) { NewArrayBase[i] = L.elem[i]; } L.elem = NewArrayBase; L.max = L.length + increment_size; }
for (int i = L.length-1; i >= index; i--) { L.elem[i + 1] = L.elem[i]; } L.elem[index] = value; L.length++;
}
void del(DynSqeList& L, int index) { if (index<0 || index>L.length) { printf("删除索引值超过边界"); return; } for (int i = index; i < L.length-1; i++) { L.elem[i] = L.elem[i + 1]; } L.length--; }
void modify(DynSqeList& L, int index, int value) { if (index<0 || index>L.length) { printf("修改索引值超过边界"); return; } L.elem[index] = value; }
int select(DynSqeList& L, int index) { if (index<0 || index>L.length) { printf("查询索引值超过边界"); return -1; } int select_value = L.elem[index]; return select_value; }
void print(DynSqeList& L) { for (int i = 0; i < L.length-1; i++) { printf("%d", L.elem[i]); } printf("\n"); }
int main() { DynSqeList L; L.length = 0; init(L); print(L);
int insert_index = 0; int insert_value = 9; insert(L, insert_index, insert_value); print(L);
int del_index = 0; del(L, del_index); print(L);
int modify_index = 1; int modify_value = 9; modify(L, modify_index, modify_value); print(L);
int select_index = 1; int select_value = select(L, select_index); printf("%d", select_value);
return 0; }
|