线性表的定义:
线性表是零个或多个数据元素的集合;
线性表中的数据元素之间是有顺利的
线性表中的数据元素个数是有限的
线性表中的数据元素的类型必须相同
接下来看看线性表几个重要的操作,创建,添加,删除,清空,查找。
// 线性表
#include <iostream>
#include "stdlib.h"
#include "string.h"
using namespace std;
//线性表结构的定义
typedef struct SeqList
{
int capacity;
int length;
int *node; //指针指向内存空间
}TSeqList;
TSeqList* SeqList_Create(int capacity);
void SeqList_Clear(TSeqList *list);
int SeqList_Length(TSeqList *list);
int SeqList_Capacity(TSeqList *list);
int SeqList_Insert(TSeqList *list, int node, int pos);
int SeqList_Get(TSeqList *list, int pos);
int SeqList_Delete(TSeqList *list, int pos);
void Print_SeqList(const TSeqList *list);
TSeqList* SeqList_Create(int capacity)
{
TSeqList *tmp = NULL;
tmp = (TSeqList *)malloc(sizeof(TSeqList));
if (tmp == NULL)
{
return NULL;
}
tmp->node = (int *)malloc(sizeof(int *) * capacity);
if (tmp->node == NULL)
{
return NULL;
}
tmp->capacity = capacity;
tmp->length = 0;
return tmp;
}
void SeqList_Clear(TSeqList *list)
{
if (list == NULL)
{
return;
}
if (list->node != NULL)
{
free(list->node);
}
free(list);
return;
}
int SeqList_Length(TSeqList *list)
{
if (list == NULL)
{
return -1;
}
return list->length;
}
int SeqList_Capacity(TSeqList *list)
{
if (list == NULL)
{
return -1;
}
return list->capacity;
}
int SeqList_Insert(TSeqList *list, int node, int pos)
{
int i = 0;
if (list == NULL || pos < 0)
{
return -1;
}
//判断是否满了
if (list->length >= list->capacity)
{
return -2;
}
if (pos > list->length)
{
pos = list->length;
}
for (i = list->length; i > pos; i--)
{
list->node[i] = list->node[i - 1];
}
list->node[i] = node;
list->length++;
}
int SeqList_Delete(TSeqList *list, int pos)
{
int i = 0;
if (list == NULL || pos < 0)
{
return -1;
}
for (i = pos + 1; i < list->length; i++)
{
list->node[i - 1] = list->node[i];
}
list->length--;
return 0;
}
int SeqList_Get(TSeqList *list, int pos)
{
if (list == NULL || pos < 0 || list->length < pos)
{
return -1;
}
return list->node[pos];
}
void Print_SeqList(TSeqList *list)
{
int i = 0;
cout << "number : " << endl;
for (; i < SeqList_Length(list); i++)
{
cout << list->node[i] << "\t";
}
cout << endl;
}
int main()
{
TSeqList * list = SeqList_Create(10);
SeqList_Insert(list, 1, 0); //头插法
SeqList_Insert(list, 2, 0);
SeqList_Insert(list, 7, 0);
SeqList_Insert(list, 4, 0);
SeqList_Insert(list, 8, 0);
Print_SeqList(list);
cout << "pos :" << SeqList_Get(list, 1) << endl;
SeqList_Delete(list, 0);
Print_SeqList(list);
SeqList_Clear(list);
system("pause");
return 0;
}