线性表是最基本、最简单、也是最常用的一种数据结构。线性表(linear list)是数据结构的一种,一个线性表是n个具有相同特性的数据元素的有限序列,每个数据元素可能会有多个数据项。
线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的(注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储,但是把最后一个数据元素的尾指针指向了首位结点)。——来自百度。
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;
typedef struct Person
{
char name[32];
int age;
}DATATYPE;
typedef struct List
{
DATATYPE *head;
int clen; //线性表有效大小
int tlen; //线性表总大小
}Seqlist;
Seqlist* init_list(int size)
{
Seqlist* mlist = new Seqlist;
mlist->head = new DATATYPE;
mlist->clen = 0;
mlist->tlen = size;
return mlist;
}
void destorylist(Seqlist* mlist)
{
delete (mlist->head);
delete mlist;
mlist->head = NULL;
mlist = NULL;
cout << "线性表销毁" << endl;
}
void cleanList(Seqlist *mlist)
{
mlist->clen = 0;
}
void isemptyList(Seqlist *mlist)
{
if (mlist->clen == 0)
{
cout << "这还是一个空表" << endl;
}
}
//尾插
void tailInsert(Seqlist *mlist, DATATYPE *data)
{
if (mlist->clen < mlist->tlen) //判断线性表是否满了
{
//mlist->head[mlist->clen] = *data;
strcpy(mlist->head[mlist->clen].name, data->name);
mlist->head[mlist->clen].age = data->age;
mlist->clen++;
}
else
{
cout << "线性表已满" << endl;
}
}
//在指定位置插入数据
void posInsert(Seqlist *mlist, int pos, DATATYPE *data)
{
if (mlist->clen < mlist->tlen)
{
for (int i = 0; i < mlist->clen - pos; ++i)
{
mlist->head[mlist->clen - i] = mlist->head[mlist->clen - i - 1];
}
mlist->head[pos] = *data;
mlist->clen++;
}
else
{
cout << "线性表已满" << endl;
}
}
//查找
DATATYPE* findData(Seqlist* mlist, char *pname)
{
DATATYPE *tmp = NULL;
for (int i = 0; i < mlist->clen;++i)
{
if (0 == strcmp(mlist->head[i].name, pname))
{
tmp = &(mlist->head[i]);
return tmp;
}
}
return NULL;
}
//更改
int reviseData(Seqlist* mlist, char *pname, DATATYPE *data)
{
DATATYPE* res = findData(mlist, pname);
if (NULL == res)
{
cout << "此数据不存在" << endl;
}
else
{
memcpy(res, data, sizeof(DATATYPE));
}
return 0;
}
void showList(Seqlist *mlist)
{
cout << "数据量为:" << mlist->clen << endl;
for (int i = 0; i < mlist->clen;++i)
{
cout <<"名字:"<< mlist->head[i].name<<" " <<"年龄:"<<mlist->head[i].age << endl;
}
}
int main()
{
Seqlist *m_list = init_list(5);
DATATYPE data1;
memset(&data1, 0, sizeof(data1));
data1.age = 15;
strcpy(data1.name, "小当家");
tailInsert(m_list, &data1);
showList(m_list);
DATATYPE data2[3] =
{
{"大当家",30},
{"二当家",25},
{"三当家",30},
};
tailInsert(m_list, &data2[0]);
tailInsert(m_list, &data2[1]);
tailInsert(m_list, &data2[2]);
showList(m_list);
cout << "----------------------------------------------------------" << endl;
cout << "查找数据:" << endl;
DATATYPE* res = findData(m_list, "大当家");
if (res == NULL)
{
cout << "此数据不存在" << endl;
}
else
{
cout << res->name << " " << res->age << endl;
}
cout << "----------------------------------------------------------" << endl;
cout << "更改数据:" << endl;
DATATYPE data3 = { "张三",30 };
reviseData(m_list, "小当家", &data3);
showList(m_list);
system("pause");
return 0;
}