0 引言
嵌入式对数据结构要求到不是特别的高,但是在学习操作系统时往往需要理解一些常见的数据结构,并且在面试的时候也会进行适当的考察。因此,本文对嵌入式常见的数据结构进行介绍。
文章主要分为三部分:线性表,栈,队列。按照这三种数据类型的存储形式又能各自分为两部分:顺序存储结构,链式存储结构。有的数据结构在顺序存储结构中还能分出顺序型和环形(如队列)。有的数据结构在链式存储结构中还能分出单链,双链,循环链(如链表)。
通过C/C++语言实现上述数据结构的创建,初始化,插入,删除等等基本运算,并将代码贴出以供学习查阅。
1 线性表
1.1 顺序表
1.1.1 定义类型
//以Student举例
typedef struct Student
{
int Num;
char Sex;
char * Name;
}Student;
typedef struct StudentList
{
Student Stu[5];
int Length;
}StudentList;
1.1.2 相关操作
void CreatList(StudentList * & L, Student Stu[], int n);
void InitList(StudentList * & L);
void DestroyList(StudentList * L);
bool ListEmpty(StudentList * L);
int ListLength(StudentList * L);
void ListDisp(StudentList * L);
int LocateElem(StudentList * L, Student E);
bool GetElem(StudentList * L, int i, Student & E);
bool InsertList(StudentList * L, int i, Student E);
bool DeleteList(StudentList * L, int i, Student & E);
1.1.3 相关操作的实现
//0建立顺序表
void CreatList(StudentList * & L, Student Stu[], int n)
{
int i;
L = (StudentList *)malloc(sizeof(StudentList));
for (i = 0; i < n; i++)
L->Stu[i] = Stu[i];
L->Length = n;
}
//1初始化顺序表
void InitList(StudentList * & L)
{
L = (StudentList *)malloc(sizeof(StudentList));
L->Length = 0;
}
//2销毁顺序表
void DestroyList(StudentList * L)
{
free(L);
L = NULL;
}
//3判断顺序表是否为空
bool ListEmpty(StudentList * L)
{
return (L->Length == 0);
}
//4输出顺序表长度
int ListLength(StudentList * L)
{
return L->Length;
}
//5输出顺序表内容
void ListDisp(StudentList * L)
{
printf("Length:%d\n\n", ListLength(L));
for (int i = 0; i < L->Length; i++)
{
printf("Name:%s\n", L->Stu[i].Name);
printf("Num:%d\n", L->Stu[i].Num);
printf("Sex:%c\n\n", L->Stu[i].Sex);
}
}
//6按值搜索顺序表,输出索引
int LocateElem(StudentList * L, Student E)
{
int i = 0;
while (i < L->Length && !((L->Stu[i].Name == E.Name) && (L->Stu[i].Num == E.Num) && (L->Stu[i].Sex == E.Sex)))
i++;
if (i == L->Length)
return 0;
else
return i+1;
}
//7按索引搜索顺序表,得到元素
bool GetElem(StudentList * L, int i, Student & E)
{
if (i<1 || i>L->Length)
return false;
else
{
E = L->Stu[i - 1];
return true;
}
}
//8顺序表插入元素
bool InsertList(StudentList * L, int i, Student E)
{
if (i<1 || i>L->Length + 1)
return false;
else
{
i--;
for (int j = (L->Length-1); j >= i; j--)
L->Stu[j + 1] = L->Stu[j];
L->Stu[i] = E;
L->Length++;
return true;
}
}
//9顺序表删除元素
bool DeleteList(StudentList * L, int i, Student & E)
{
if (i<1 || i>L->Length + 1)
return false;
else
{
i--;
E = L->Stu[i];
for (int j = i; j < (L->Length - 1); j++)
L->Stu[j] = L->Stu[j + 1];
L->Length--;
return true;
}
}
1.2 链表
1.2.1 定义类型
/*************************单链表*************************/
//以Student举例
typedef struct Student