C语言实现数据结构之线性表

线性表相关知识

下面给出一个简单的C语言实现,若有其他需求可在该基础上自行添加

#include<stdio.h>
#include<stdlib.h>
//数据结构之线性表
//特点
//优点:无须为表示表中元素之间的逻辑关系而增加额外的存储空间,可以快速地存储表中任何位置的元素
//缺点:插入和删除操作需要移动大量元素 当线性表长度变化较大时,难以确定存储空间的容量  会造成存储空间的”碎片”


//线性表存储结构
#define MaxSize 20  //最大存储空间 下标0-19
typedef int ElemType;  //存储的类型,这里以int为例
typedef struct
{
	ElemType data[MaxSize];  //数组,用来存储线性表中的元素
	int length; //记录当前长度
}SqList;    //SqList为当前结构体名 

//初始化线性表
bool InitList(SqList *L)
{
	if (L != NULL)
	{
		L->length = 0;
		return true;
	}
	else
	{
		return false;
	}
}

//传递数组A[],给线性表赋值
bool CreateList(SqList*L,ElemType* A,int A_size)
{
	if ((A_size+L->length)>MaxSize)
	{
		return false;
	}
	else
	{


		int A_index = 0;
		int i = L->length;
		int j = L->length + A_size;
		for (i; i < j; ++i)
		{
			L->data[i] = A[A_index];
			L->length++;
			++A_index;
		}
		return true;
	}
}

//打印当前线性表内容
void PrintfSqList(SqList* L)
{
		int x = 0;
		for (x; x < L->length; ++x)
		{
			printf("%d ",L->data[x]);
		}
		printf("\n");
}

//线性表插入,在第i个位置插入元素e,其后元素依次后移
//i默认为L->length,即默认直接插入线性表尾部
bool InsertList(SqList*L,ElemType e, int i)
{
	if (L->length == MaxSize) //线性表满了
	{
		return false;
	}
	if (i<1 || i>L->length + 1)
	{
		return false;
	}
	else
	{
		//思路,将要插入的元素依次后移,在将该位置的元素赋值为e
		//例 1 2 4 5 6 * * * * 
		//   1 2 2 4 5 6 * * *
		//   1 2 3 4 5 6 * * *
		int end_index = L->length; //指向线性表当前最后的一个元素的下一个位置
		for (end_index; end_index > i-1; end_index--)
		{
			L->data[end_index] = L->data[end_index-1];
		}
		L->data[i - 1] = e;
		++L->length;
		return true;
	}
}

//删除第i号元素
bool DeleteListI(SqList*L,int i)
{
	if (L->length == 0) //线性表为空
	{
		return false;
	}
	else if (i<1 || i>MaxSize)//删除位置不存在
	{
		return false;
	}
	else if (i == MaxSize)  //删除尾部元素
	{
		--L->length;
		return true;
	}
	else
	{
		for (i; i < L->length; i++)
		{
			L->data[i - 1] = L->data[i];
		}
		L->length--;
	}

}


//主程序 用来测试
int main()
{
	SqList L;
	//初始化线性表
	if (InitList(&L))
	{
		printf("初始化线性表成功\n");
	}
	else
	{
		printf("初始化线性表失败\n");
	}
	//利用数组为线性表赋值,单个赋值由插入方法完成
	int a[10] = {0,1,2,3,4,5,6,7,8,9};
	CreateList(&L,a,10);
	int b[5] = { 10,11,12,13,14 };
	CreateList(&L,b,5);
	int c[5] = { 15,16,17,18,19 };
	CreateList(&L,c,4);
	PrintfSqList(&L);
	printf("L->length:%d\n", L.length);
	//在第20位置插入19
	InsertList(&L,19,20);
	PrintfSqList(&L);
	printf("L->length:%d\n",L.length);
	//删除第4位置的元素
	DeleteListI(&L,4);
	PrintfSqList(&L);
	printf("L->length:%d\n", L.length);
	//在第1位置插入-1
	InsertList(&L,-1,1);
	PrintfSqList(&L);
	printf("L->length:%d\n", L.length);
	return 0;
}

由于个人实力有限,若有错误,欢迎指出

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值