seqlist.h
#ifndef _SEQ_LIST_H
#define _SEQ_LIST_H
typedef void SeqList;
typedef void SeqNode;
SeqList * SeqList_Create(int capacity);
void SeqList_Destory(SeqList *list);
int SeqList_Insert(SeqList *list,SeqNode *node,int pos);
SeqNode *SeqList_Delete(SeqList *list, int pos);
int SeqList_Length(SeqList *list);
SeqNode *SeqList_Get(SeqList *list,int pos);
#endif
seqlist.cpp
#include "seqlist.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct _tag_SeqList
{
int capacity;
int lenght;
int *pNode;
}TSeqList;
SeqList * SeqList_Create(int capacity)
{
TSeqList *tList = NULL;
tList = (TSeqList *)malloc(sizeof(TSeqList) + sizeof(int*)*capacity);
tList->capacity = capacity;
tList->pNode = (int *)(tList + 1);
tList->lenght = 0;
return (SeqList *)tList;
}
void SeqList_Destory(SeqList *list)
{
TSeqList *tList = (TSeqList *)list;
if (tList != NULL)
{
free(tList);
}
}
int SeqList_Insert(SeqList *list, SeqNode *node, int pos)
{
TSeqList *tList = (TSeqList *)list;
if (pos < 0 || pos >= tList->capacity || tList == NULL)
{
return -1;
}
if (tList->lenght == tList->capacity)
{
return -2;
}
int i = tList->lenght;
while (i > pos)
{
tList->pNode[i] = tList->pNode[i - 1];
i--;
}
tList->pNode[pos] = (int)node;//save address
tList->lenght++;
return 0;
}
SeqNode *SeqList_Delete(SeqList *list, int pos)
{
TSeqList *tList = (TSeqList *)list;
if (pos < 0 || pos >= tList->capacity || tList == NULL)
{
return NULL;
}
int i = pos + 1;
SeqNode *node = (SeqNode *)(tList->pNode[pos]);
while (i < tList->lenght)
{
tList->pNode[i - 1] = tList->pNode[i];
i++;
}
tList->lenght--;
return node;
}
int SeqList_Length(SeqList *list)
{
TSeqList *tList = (TSeqList *)list;
return tList->lenght;
}
SeqNode *SeqList_Get(SeqList *list, int pos)
{
TSeqList *tList = (TSeqList *)list;
return (SeqNode *)(tList->pNode[pos]);
}
client.cpp
#include "seqlist.h"
#include <stdio.h>
typedef struct _Teacher
{
char name[64];
int age;
}Teacher;
int main()
{
SeqList * list = NULL;
list = SeqList_Create(100);
Teacher t1, t2, t3, t4;
t1.age = 10;
t2.age = 20;
t3.age = 30;
t4.age = 40;
SeqList_Insert(list, &t1, 0);
SeqList_Insert(list, &t2, 0);
SeqList_Insert(list, &t3, 0);
SeqList_Insert(list, &t4, 0);
int i = 0;
for (i = 0; i < SeqList_Length(list); i++)
{
Teacher * teacher = (Teacher*)SeqList_Get(list, i);
printf("age:%d\n", teacher->age);
}
Teacher * tmp = NULL;
tmp = (Teacher*)SeqList_Delete(list, 0);
printf("age:%d\n", tmp->age);
tmp = (Teacher*)SeqList_Delete(list, 0);
printf("age:%d\n", tmp->age);
tmp = (Teacher*)SeqList_Delete(list, 0);
printf("age:%d\n", tmp->age);
tmp = (Teacher*)SeqList_Delete(list, 0);
printf("age:%d\n", tmp->age);
SeqList_Destory(list);
return 0;
}