一 使用顺序存储线性表
先写出各个函数的功能
这个·单独列出一个头文件,命名为seqlist,h
#ifndef __MY_SEQLIST_H__
#define __MY_SEQLIST_H__
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);//求线性表的有效元素个数
int SeqList_Capacity(SeqList* list);//求线性表的长度
int SeqList_Insert(SeqList* list, SeqListNode* node, int pos);//在指定位置插入一个元素
SeqListNode* SeqList_Get(SeqList* list, int pos);//得到一个元素
SeqListNode* SeqList_Delete(SeqList* list, int pos);
#endif //__MY_SEQLIST_H__
//定义一个结构体控制头
typedef struct _tag_SeqList
{
int capacity;
int length;
unsigned int *node;//指向存储数据的地址
}TSeqList;
第一步:创建一个线性表
//创建一个线性表
SeqList* SeqList_Creat(int capacity)
{
TSeqList *ret = NULL;
if(capacity < 0){
return NULL;
}
//申请控制头和存储数据的地址
ret = (TSeqList *)malloc(sizeof(TSeqList)+sizeof(unsigned int)*capacity);
if(ret < NULL){
return NULL;
}
memset(ret, 0, sizeof(sizeof(TSeqList)+sizeof(unsigned int)*capacity));
//给控制头赋值
ret->capacity = capacity;
ret->length = 0;
ret->node = (unsigned int *)(ret+1);
return ret;
}
销毁一个线性表
void SeqList_Destroy(SeqList* list)
{
if(list == NULL){
return;
}
free(list);
}
因为申请的时候只用了一个malloc所以一次free就可以把线性表的所有申请空间删除,
清除一个线性表
void SeqList_Clear(SeqList *list)
{
TSeqList *tList = NULL;
if(list == NULL){
return;
}
tList = (TSeqList *)list;
tList->length = 0;
}
int SeqList_Length(SeqList* list)
{
TSeqList *tList = NULL;
tList = (TSeqList *)list;
if(list == NULL){
return -1;
}
return tList->length;
}
求线性表的长度
int SeqList_Capacity(SeqList* list)
{
TSeqList *tList = NULL;
tList = (TSeqList *)list;
if(list == NULL){
return -1;
}
return tList->capacity;
}
int SeqList_Insert(SeqList* list, SeqListNode* node, int pose)
{
int i = 0;
TSeqList *tList = NULL;
tList = (TSeqList *)list;
if(list == NULL || node == NULL)
{
return -1;
}
//看看是不是满了
if(tList->length>=tList->capacity){
return -1;
}
//插入位置
if(pose > tList->length){
tList->length = pose;
}
//插入算法
for(i = tList->length; i > pose; i--){
tList->node[i] = tList->node[i-1];
}
tList->node[pose] = (unsigned int)node;
tList->length++;
return 1;
}
得到线性表中指定的元素
SeqListNode* SeqList_Get(SeqList* list, int pose)
{
SeqListNode* ret = NULL;
TSeqList *tList = NULL;
tList = (TSeqList *)list;
if(list == NULL || pose < 0 || pose >= tList->length){
return NULL;
}
ret = (SeqListNode*)tList->node[pose];
return ret;
}
删除线性表中的元素
SeqListNode* SeqList_Delete(SeqList* list, int pose)
{
int i = 0;
SeqListNode* ret = NULL;
TSeqList *tList = NULL;
tList = (TSeqList *)list;
if(list == NULL || pose < 0 || pose >= tList->length){
return NULL;
}
ret = (SeqListNode*)tList->node[pose];
//删除算法
for(i=pose+1; i<tList->length; i++){
tList->node[i-1] = tList->node[i];
}
tList->length--;
return tList;
}
总结:在这个程序里面,不注意线性表中的节点是什么类型,只负责将数据整合在一起