测试函数:文件名 test_array_list.c
#include<stdio.h>
#include "array_list.h"
int main()
{
int value;
seq_list seq_list_array;
list_init(&seq_list_array); //不加这句的话会出现多一个元素的情况,数值是1
list_insert_element(&seq_list_array, 1, 5);
list_insert_element(&seq_list_array, 2, 7);
list_insert_element(&seq_list_array, 3, 6);
list_insert_element(&seq_list_array, 2, 10);
print_list(seq_list_array);
list_get_element(seq_list_array, 2 ,&value);
printf("The value is %d\n", value);
print_list(seq_list_array);
list_del_element(&seq_list_array, 3, &value);
printf("The value is %d\n", value);
print_list(seq_list_array);
}
#ifndef _ARRAY_LIST_H
#define _ARRAY_LIST_H
#define ERROR 0
#define OK 1
#define MAX_SIZE 10
typedef int status;
typedef int data_type;
typedef struct
{
data_type data[MAX_SIZE];
int length;
}seq_list;
void list_init(seq_list *L);
status list_get_element(seq_list L, int location, data_type *e);
status list_insert_element(seq_list *L, int location, data_type e);
status list_del_element(seq_list *L, int location, data_type *e);
void print_list(seq_list L);
#endif
#include<stdio.h>
#include "array_list.h"
void list_init(seq_list *L)
{
L->length = 0;
}
status list_get_element(seq_list L, int location, data_type *e)
{
if(L.length == 0 || location < 1 || location > L.length)
return ERROR;
*e = L.data[location-1];
return OK;
}
status list_insert_element(seq_list *L, int location, data_type e)
{
int k;
if(L->length == MAX_SIZE)
return ERROR;
if(location < 1 || location > L->length + 1)
return ERROR;
if(location <= L->length)
{
for(k=L->length-1; k>=location-1; k--)
L->data[k+1] = L->data[k];
}
L->data[location-1] = e;
L->length++;
return OK;
}
status list_del_element(seq_list *L, int location, data_type *e)
{
int k;
if(L->length == 0)
return ERROR;
if(location < 1 || location > L->length)
return ERROR;
*e = L->data[location-1];
if(location < L->length)
{
for(k=location; k<L->length; k++)
L->data[k-1] = L->data[k];
}
L->length--;
return OK;
}
void print_list(seq_list L)
{
int k;
printf("print the whole list\n");
printf("The length of list is %d\n", L.length);
for(k=0; k<L.length; k++)
printf("%d\t", L.data[k]);
printf("\n");
}