最近复习了C语言的相关知识,实现了数据结构中的顺序表。
下面是Main.c文件:
#include "SeqList.h"
#include <stdio.h>
int main()
{
SeqList* list = SeqListCreate();
if(list != NULL)
{
printf("顺序表容量为:%d\n", SeqListCapacity(list));
printf("顺序表长度为:%d\n", SeqListLength(list));
printf("插入状态:%d\n", SeqListInsert(list, 0, 0));
printf("插入状态:%d\n", SeqListInsert(list, 1, 1));
printf("插入状态:%d\n", SeqListInsert(list, 2, 2));
printf("插入状态:%d\n", SeqListInsert(list, 3, 3));
printf("插入状态:%d\n", SeqListInsert(list, 9, 4));
printf("此时顺序表长度为:%d\n", SeqListLength(list));
SeqListDelete(list, 0, NULL);
SeqListDelete(list, 0, NULL);
printf("此时顺序表长度为:%d\n", SeqListLength(list));
printf("删除状态:%d\n", SeqListDelete(list, 1, NULL));
printf("此时顺序表长度为:%d\n", SeqListLength(list));
list = SeqListDestroy(list);
}
return 0;
}
下面是SeqList.h文件:
#ifndef __SEQLIST_H__
#define __SEQLIST_H__
typedef int DataType;
#define deBug() printf("File = %s\nLine = %n", __FILE__, __LINE__)
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#ifndef __cplusplus
typedef int Bool;
#define true 1
#define false 0
#else
typedef bool Bool;
#endif
#define MALLOC(type, size) (type*)malloc(sizeof(type) * size)
#define FREE(p) (free(p), p = NULL)
typedef struct
{
DataType space[MAXSIZE];
int size;
} SeqList;
SeqList* SeqListCreate(void);
SeqList* SeqListDestroy(SeqList *list);
int SeqListLength(SeqList *list);
int SeqListCapacity(SeqList *list);
Bool SeqListInsert(SeqList *list, int i, DataType data);
Bool SeqListDelete(SeqList *list, int i, DataType *data);
Bool SeqListSet(SeqList *list, int i, DataType data);
Bool SeqListGet(SeqList *list, int i, DataType *data);
#endif
下面是SeqList.c文件:
#include "SeqList.h"
SeqList* SeqListCreate(void)
{
SeqList *ret = MALLOC(SeqList, 1);
if(ret != NULL) ret->size = 0;
return ret;
}
SeqList* SeqListDestroy(SeqList *list)
{
return FREE(list);
}
int SeqListLength(SeqList *list)
{
return (list != NULL) ? list->size : -1;
}
int SeqListCapacity(SeqList *list)
{
return (list != NULL) ? MAXSIZE : -1;
}
Bool SeqListInsert(SeqList *list, int i, DataType data)
{
Bool ret = (list != NULL) && (i >= 0) && (i <= list->size) && (list->size < MAXSIZE);
if(ret)
{
int j;
for(j = list->size - 1; j >= i; j--)
{
list->space[j + 1] = list->space[j];
}
list->space[j] = data;
list->size++;
}
return ret;
}
Bool SeqListDelete(SeqList *list, int i, DataType *data)
{
Bool ret = (list != NULL) && (i >= 0) && (i < list->size);
if(ret)
{
if(data != NULL) *data = list->space[i];
for(; i < list->size - 1; i++)
{
list->space[i] = list->space[i + 1];
}
list->size--;
}
return ret;
}
Bool SeqListSet(SeqList *list, int i, DataType data)
{
return ((list != NULL) && (i >= 0) && (i < list->size)) ? (list->space[i] = data, true) : false;
}
Bool SeqListGet(SeqList *list, int i, DataType *data)
{
return ((list != NULL) && (i >= 0) && (i < list->size) && (data != 0)) ? (*data = list->space[i], true) : false;
}
不知道什么原因,使用Dev c++编译这个程序会在free掉顺序表时出错。改使用Qt重新编译,无错误无警告。下面是运行结果: