代码
#include
#include
typedef int E;
struct List{
E * array;
int capacity;
int size;
};
typedef struct List * ArrayList;
_Bool initList(ArrayList list){
list->array = malloc(sizeof (E) * list->capacity);
if(list->array == NULL) return 0;
list->capacity = 10;
list->size=0;
return 1;
}
_Bool insertList(ArrayList list, E element, int index){
if(index < 1 || index > list->size + 1) return 0;
if(list->size == list->capacity) {
int newCapacity = list->capacity + (list->capacity >> 1);
E * newArray = realloc(list->array, newCapacity * sizeof(E));
if(newArray == NULL) return 0;
list->array = newArray;
list->capacity = newCapacity;
}
for (int i = list->size; i > index - 1; --i)
list->array[i] = list->array[i - 1];
list->array[index - 1] = element;
list->size++;
return 1;
}
void printList(ArrayList list){
for (int i = 0; i < list->size; ++i)
printf("%d ", list->array[i]);
printf("\n");
}
_Bool deleteList(ArrayList list, int index){
if(index < 1 || index > list->size) return 0;
for (int i = index - 1; i < list->size - 1; ++i)
list->array[i] = list->array[i + 1];
list->size--;
return 1;
}
int sizeList(ArrayList list){
return list->size;
}
E * getList(ArrayList list, int index){
if(index < 1 || index > list->size) return NULL;
return &list->array[index - 1];
}
int findList(ArrayList list, E element){
for (int i = 0; i < list->size; ++i) {
if(list->array[i] == element) return i + 1;
}
return -1;
}
int main(){
struct List list;
if(initList(&list)){
for (int i =0; i<30; i++){
insertList(&list, i*10, i+1);
}
deleteList(&list, 10);
deleteList(&list, 10);
printList(&list);
printf("获取数组容量:%d\n", list.capacity);
printf("按位置获取元素:%d\n", *getList(&list, 3));
printf("按值查找元素位置:%d\n", findList(&list, 30));
} else{
printf("顺序表初始化失败,无法启动程序!");
}
}
- 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
运行效果