源码
#include <stdio.h>
#include <stdlib.h>
typedef int E;
struct List {
E * array;
int capacity;
int size;
};
typedef struct List * ArrayList;
int initList(ArrayList list) {
list->array = malloc(sizeof(E) * 10);
if (list->array == NULL) return 0;
list->capacity = 10;
list->size = 0;
return 1;
}
int insertList(ArrayList list, E element, int index) {
if (index > list->size + 1 || index < 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;
}
int deleteList(ArrayList list,int index) {
if (index < 1 || index > list->size) return 0;
int deleteNum = list->array[index - 1];
for (int i = index - 1; i < list->size; i++) {
list->array[i] = list->array[i + 1];
list->size--;
}
return deleteNum;
}
int sizeList(ArrayList list) {
return list->size;
}
E * getListElement(ArrayList list, int index) {
if (index < 1 || index > list->size) return NULL;
return &list->array[index - 1];
}
int findListElement(ArrayList list, E element) {
for (int i = 0; i < list->size; i++ ) {
if (list->array[i] == element) return i + 1;
return -1;
}
}
void printList(ArrayList list) {
for (int i = 0; i < list->size; i++) {
printf("%d ", list->array[i]);
}
printf("\n");
}
int main(void) {
struct List list;
if (initList(&list)) {
for (int i = 0; i < 10; i++) {
insertList(&list, i + 1, i + 1);
}
printList(&list);
printf("%d\n", *getListElement(&list, 10));
printf("%d", findListElement(&list, 100));
}else {
printf("顺序表初始化失败,无法启动!");
}
free(&list);
}