Head.H
typedef struct _seqlist
{
int *data;
int len;
int size;
} SeqList, *seqlist;
seqlist CreateSeqList(int size);
void AddVal(seqlist L, int data);
void ListInsert(seqlist L, int pos, int data);
void PrintSeqList(seqlist L);
Function.C
seqlist CreateSeqList(int size)
{
seqlist L = (seqlist)malloc(sizeof(SeqList));
L->data = (int*)malloc(sizeof(int) * size);
L->len = 0;
L->size = size;
return L;
}
void AddVal(seqlist L, int data)
{
if (L->len == L->size)
{
L->data = (int*)realloc(L->data, (L->len + 10) * sizeof(int));
L->size += 10;
}
L->data[L->len] = data;
L->len++;
}
//在pos前方插入,pos从0开始
void ListInsert(seqlist L, int pos, int data)//赋值(可改)
{
if (L->len == L->size)
{
L->data = (int*)realloc(L->data, (L->len + 10) * sizeof(int));
L->size += 10;
}
for (int i = L->len; i > pos; i--)
{
L->data[i] = L->data[i - 1];
}
L->data[pos] = data;
L->len++;
}
void PrintSeqList(seqlist L)//打印线性表内容
{
for (int i = 0; i < L->len; i++)
{
printf("%d ", L->data[i]);
}
printf("\n");
}
Main.C
void main(void)
{
seqlist L1 = CreateSeqList(5);
AddVal(L1, 1); AddVal(L1, 2); AddVal(L1, 3); AddVal(L1, 4); AddVal(L1, 5); AddVal(L1, 6); //123456
PrintSeqList(L1);
ListInsert(L1, 3, 9); //1239456
PrintSeqList(L1);
printf("%d \n", L1->len); //7
printf("%d \n", L1->size); //7
printf("\n");
system("pause");
}