1.C语言实现线性表基本功能

1.C语言实现线性表基本功能
#include<stdio.h>
#include<stdlib.h>
#define OK  1
#define ERROR 0
typedef int Status;
//定义线性表的数据结构
#define MAXSIZE 20
typedef int ElemType;
typedef struct {
	ElemType data[MAXSIZE];
	int length;            //线性表当前长度
}SqList;

//线性表的初始化
Status InitList(SqList*L) {
	//为线性表分配内存
	*L->data = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
	//线性表长度初始化为0
	L->length = 0;
	//判断内存是否分配成功
	if (L->data) {
		//分配成功则返回OK
		return OK;
	}
	//分配失败返回ERROR
	return ERROR;
}
//获取线性表的第i个元素
Status GetElem(SqList L, int i, ElemType* e) {
	//如果获取的元素位置不合适则返回ERROR
	if (L.length==0||i<1 || i>L.length) {
		return ERROR;
	}
	//获取元素成功
	*e = L.data[i-1];
	return OK;
}
//插入元素,在线性表的第i个位置插入元素e
Status ListInsert(SqList* L, int i, ElemType e) {
	//选择合适的位置插入
	if (L->length == MAXSIZE || i<1 || i>L->length + 1) {
		return ERROR;
	}
	//如果插入的位置不在表尾,则进入for循环
	if (i <= L->length) {
	for (int j = L->length; j > i - 1; j--) {
		L->data[j] = L->data[j - 1];
	}
}
	//第i个位置下标为i
	L->data[i - 1] = e;
	//表长加一
	L->length++;
	return OK;
}
//删除线性表中第i个位置的元素,并且用e返回其值
Status Listdelete(SqList* L, int i, ElemType* e) {
	//选择合适的位置删除
	if (L->length == 0 || i<1 || i>L->length) {
		return ERROR;
	}
	//返回删除的元素值
	*e = L->data[i - 1];
	//如果删除的不是表尾元素
	if (i < L->length) {
		for (int j = i - 1; j < L->length-1; j++) {
			L->data[j] = L->data[j + 1];
		}
	}
	//表的长度减一
	L->length--;
	//删除元素成功
	return OK;
}
//遍历线性表的所有元素
Status printList(const SqList* L) {
	if (L->length == 0) {
		return ERROR;
	}
	for (int i = 0; i < L->length; i++) {
		if (i == L->length - 1) {
			printf("%d\n", L->data[i]);
		}
		else {
			printf("%d-->", L->data[i]);
		}
	}
	return OK;
}
//测试代码
void main() {
	//线性表的初始化
	SqList L;
	InitList(&L);
	for (int i = 0; i < 10; i++) {
		L.data[i] = i;
		L.length++;
	}
	//在线性表的第3个位置插入元素e
	ElemType e = 18;
	ListInsert(&L, 3, e);
	printList(&L);
	//删除线性表中第3个元素,并用e变量返回该元素
	Listdelete(&L, 3, &e);
	printList(&L);
	printf("%d\n", e);
	//获取线性表中第3个元素,并用e变量返回该元素
	GetElem(L, 3, &e);
	printList(&L);
	printf("%d\n", e);
	system("pause");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

善水无为

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值