seqlist.h
#pragma once
typedef void SeqList;
typedef void SeqListNode;
SeqList *SeqList_Create(int capacity);
void SeqList_Destroy(SeqList *list);
void SeqList_Clear(SeqList *list);
int SeqList_Length(SeqList*list);
SeqListNode *SeqList_Insert(SeqList *list, SeqListNode *node, int pos);
SeqListNode *SeqList_Get(SeqList *list, int pos);
SeqListNode *SeqList_Delete(SeqList *list, int pos);
seqlist.c
//内部实现
typedef struct _tag_SeqList
{
int capacity; //容量
int length; //记录当前使用多少
unsigned int *node; //相当于 int node[0];
}TSeqList;
//创建
SeqList *SeqList_Create(int capacity)
{
TSeqList *ret = (TSeqList *)malloc(sizeof(TSeqList)+sizeof(unsigned int )*capacity);
if (ret == NULL)
{
return NULL;
}
//初始化内存
memset(ret, 0, sizeof(TSeqList) + sizeof(unsigned int)*capacity);
ret->length = 0;
ret->capacity = capacity;
ret->node = ret + 1; //node节点等于首地址偏移到一一个/
return ret;
}
//销毁
void SeqList_Destroy(SeqList *list)
{
TSeqList *ret = (TSeqList *)list;
if (ret != NULL)
free(ret);
}
//清空
void SeqList_Clear(SeqList *list)
{
TSeqList *ret = (TSeqList *)list;
if (ret != NULL)
{
ret->length = 0;
}
}
//长度
int SeqList_Length(SeqList*list)
{
TSeqList *ret = (TSeqList *)list;
if (ret != NULL)
{
return ret->length;
}
return 0;
}
//插入
SeqListNode *SeqList_Insert(SeqList *list, SeqListNode *node, int pos)
{
TSeqList *ret = (TSeqList *)list;
if (ret == NULL || node == NULL || pos<0)
{
return NULL;
}
if (ret->length < pos)
{
pos = ret->length;
}
for (int i = ret->length; i > pos; i--)
{
//把元素往后移动
ret->node[i] = ret->node[i - 1];
}
ret->node[pos] = (unsigned int)node;//新插入的
ret->length++;
return node;
}
//获取
SeqListNode *SeqList_Get(SeqList *list, int pos)
{
TSeqList *ret = (TSeqList *)list;
if (ret == NULL || pos<0)
{
return NULL;
}
if (ret->length < pos)
{
pos = ret->length;
}
return ret->node[pos];
}
//删除
SeqListNode *SeqList_Delete(SeqList *list, int pos)
{
TSeqList *ret = (TSeqList *)list;
if (ret == NULL || pos<0)
{
return NULL;
}
if (ret->length < pos)
{
pos = ret->length;
}
SeqListNode *node = (SeqListNode *)ret->node[pos];
for (int i = pos; i < ret->length; i++)
{
ret->node[i] = ret->node[i + 1];
}
ret->length--;
return node;
}
main.c
#include "seqlist.h"
#include "stdlib.h"
#include "stdio.h"
typedef struct _Teacher
{
SeqListNode *head;
int age;
}Teacher;
void main()
{
SeqList *list = SeqList_Create(10);
if (list == NULL)
return ;
Teacher t1, t2, t3;
t1.age = 10;
t2.age = 20;
t3.age = 30;
SeqList_Insert(list, (SeqListNode*)&t1,0);
SeqList_Insert(list, (SeqListNode*)&t2, 0);
SeqList_Insert(list, (SeqListNode*)&t3, 0);
for (int i = 0; i < 6; i++)
{
Teacher *temp = (Teacher *)SeqList_Get(list, i);
if (temp != NULL)
{
printf("Teacher age:%d \n",temp->age);
}
}
system("pause");
}