#include 'LinearList.h' #include <stdlib.h>

int main(int argc, char* argv[]) { SqList L; int i;

//
// 初始化线性表
//
if (Initlist(&L) != OK) {
	return 0;
}

int length = 8;
for (int i = 0; i < length; i++)
{
	L.elem[i] = i * 2 + 1;
	++L.length;
}

//
// 在第 i 个元素之前插入元素
//
ListInsertBefore(&L, 5, 118);	
ListInsertBefore(&L, 13, 30);	// 插入位置非法。插入失败。

for (int i = 0; i < L.length; i++)
{
	printf("%d ", L.elem[i]);
}

printf("\n");

DestoryList(&L);

return 0;

}

/* 功能: 初始化线性表。

参数: L -- 线性表

返回值: 无 / Status Initlist(SqList L) { L->elem = malloc(MAXSIZE * sizeof(ElemType)); if (!L->elem) exit(OVERFLOW); L->length = 0; L->maxLength = MAXSIZE; return OK; }

/* 功能: 销毁线性表。

参数: L -- 线性表

返回值: 无 / void DestoryList(SqList L) { free(L->elem); L->length = 0; }

/* 功能: 在第 i 个元素之前插入一个元素。

参数: L -- 线性表 e -- 插入的元素 i -- 指定位置。从 1 开始计数。

返回值: 如果插入成功返回 OK 如果插入失败返回 ERROR / Status ListInsertBefore(SqList L, int i, ElemType e) { int j = 0; // 用于移动元素的游标

//
// TODO: 在此添加代码
//

if (i < 1 || i > L->length + 1) { return ERROR; // 插入位置非法 }

if (L->length >= MAXSIZE) {
	return ERROR;	// 线性表已满,无法插入
}

for (j = L->length - 1; j >= i - 1; j--) {
	L->elem[j + 1] = L->elem[j];	// 将第 i 个元素及之后的元素后移
}

L->elem[i - 1] = e;	// 将新元素插入到第 i 个位置
L->length++;		// 长度加 1

return OK;

}

C语言线性表插入元素代码示例 - ListInsertBefore 函数实现

原文地址: https://www.cveoy.top/t/topic/eSj3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录