最近在学数据结构,需要用C语言实现功能
上掘金一搜,发现线性表代码实现的文章里面的代码要么就是用JAVA实现,那些大学老师不一定能看得懂JAVA,要么就是咔咔把代码剪成几段放上来,根本运行不了,有的压根就不是完整的代码,就放几个函数上去
我就是不会才来看啊,想着抄一个现成的,结果我还得补全代码
经过我东拼西凑,弄出来线性表C语言实现的完整代码,自己运行了几遍没问题
// 引入包;
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 100
// 定义结构类型
typedef struct sqlist
{
int *pBase;
int length;
int size;
} SqList, *pSqList;
// 声明函数
void InitList(pSqList L);
bool AppendList(pSqList L, int elem);
bool ShowList(pSqList L);
bool InsertList(pSqList L, int position, int elem);
bool DeleteList(pSqList L, int position, int *pElem);
// 主函数
int main(void)
{
SqList L; // 定义了一个线性表变量 L
InitList(&L);
AppendList(&L, 1);
InsertList(&L, 1, 10);
int e;
DeleteList(&L, 1, &e);
ShowList(&L);
return 0;
}
// 初始化
void InitList(pSqList L)
{
printf("initList\n");
L->pBase = (int *)malloc(sizeof(SqList) * MAXSIZE);
if (NULL == L->pBase)
{
printf("fail");
exit(-1);
}
L->length = 0;
L->size = MAXSIZE;
}
// 线性表是否已满
bool IsFull(pSqList L)
{
return (L->length == L->size);
}
// 从末尾增添数据
bool AppendList(pSqList L, int elem)
{
// 异常处理
if (IsFull(L))
{
printf("线性表已满,无法增添数据!");
return false;
}
// 增添数据
L->pBase[L->length] = elem;
// 线性表结构内部变量更新
L->length++;
return true;
}
// 线性表是否为空
bool IsEmpty(pSqList L)
{
return (0 == L->length);
}
// 显示线性表内数据
bool ShowList(pSqList L)
{
// 异常处理
if (IsEmpty(L))
{
printf("线性表为空!");
return false;
}
// 遍历线性表
for (int i = 0; i < L->length; i++)
{
printf("%d ", L->pBase[i]); // %d 根据 typedef int int; 而定
}
printf("\n");
return true;
}
// 插入元素
// position取值范围:1 ~ L->length
bool InsertList(pSqList L, int position, int elem)
{
if (position < 1 || position > L->length + 1)
{
printf("error");
return false;
}
if (IsFull(L))
{
printf("error");
return false;
}
for (int i = L->length - 1; i >= position - 1; i--)
{
L->pBase[i + 1] = L->pBase[i];
}
L->pBase[position - 1] = elem;
L->length++;
return true;
}
// 删除元素
// position取值范围:1 ~ L->length
bool DeleteList(pSqList L, int position, int *pElem)
{
if (position < 1 || position > L->length)
{
printf("error");
return false;
}
if (IsEmpty(L))
{
printf("error");
return false;
}
for (int i = position; i < L->length; i++)
{
L->pBase[i - 1] = L->pBase[i];
}
L->length--;
return true;
}
// 线性表存储空间依然保留,只是将其中的数据清空
void ClearList(pSqList L)
{
// 直接将其长度置为0即可
L->length = 0;
}
`