【数据结构之线性表顺序存储】简单的数组的方式实现

线性表是数据结构中最基础的内容,虽然其理论不难理解,但是用代码实现起来每个人有不同的写法。本文用最简单的数组的方式的实现,直接在数组存入元素。实现线性表的任意位置插入元素,任意位置删除元素,获取任意位置的元素等等。



《代码 C》在win7+VS2013中编写

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ok 1
#define error 0

#define MAXSIZE 20 //存储空间的大小
typedef int ElemType;//元素的类型
typedef void list;
typedef int status;//函数的返回结果的正常与否 如ok;

typedef struct SeqList
{
	ElemType date[MAXSIZE];//用数组来存储元素,最大值为MAXSIZE
	int length;//线性表的当前长度
}SeqList;

//顺序表的初始化
status list_init(SeqList* list)
{
	list->length = 0;
	return ok;
}

//顺序表中元素的生成
status list_create(SeqList* list)
{
	int i = 0;
	srand((unsigned)time(0));//初始化随机种子
	for (i = 0; i < 10; i++)
	{
		list->date[i] = rand() % 100;//链表的数据随机存为100以内的随机数
		list->length++;
	}
	return ok;
}

//清空顺序表
status list_clear(SeqList* list)
{
	list->length = 0;
	return ok;
}
//返回顺序表中的元素个数
int list_length(SeqList* list)
{
	return list->length;
}
//获取线性表pos位置上的元素
status list_get(SeqList* list,int pos,ElemType *e)
{
	if (list->length == 0 || pos > list->length || pos < 0)
		return error;
	*e = list->date[pos];
	return ok;
}
//线性表的插入操作
status list_insert(SeqList* list, ElemType e, int pos)
{
	int i;
	SeqList *temp = NULL;//用指针接过来,不用直接操作形参
	temp = (SeqList*)list;

	if (temp->length == MAXSIZE)//线性表已满
		return error;
	if (pos<0 || pos > temp->length)//插入位置无效
		return error;
	if (pos < temp->length)
	{
		for (i = temp->length; i > pos; i--)
		{
			temp->date[i] = temp->date[i-1];
		}
	}
	temp->date[pos] = e;
	temp->length++;
	return ok;
}
//线性表的删除操作,并把删除的值用e返回
status list_delete(SeqList* list, ElemType *e, int pos)
{
	int i;
	SeqList *temp = NULL;//用指针接过来,不用直接操作形参
	temp = (SeqList*)list;

	if (pos<0 || pos >= temp->length)//删除位置无效
		return error;
	*e = temp->date[pos];//将要删除的数据放入e中
	if (pos < temp->length)
	{
		for (i = pos; i < temp->length; i++)
		{
			temp->date[i] = temp->date[i + 1];//元素前移
		}
	}
	temp->length--;
	return ok;
}

int main()
{
	SeqList L;
	int i;
	ElemType element;
	list_init(&L);//初始化线性表的长度
	list_create(&L);//生成线性表中的元素
	for (i = 0; i < list_length(&L); i++)
	{
		list_get(&L, i, &element);
		printf("线性表中的数据%d为:%d\n",i, element);
	}
	list_insert(&L, 0, 10);
	list_insert(&L, 1, 10);
	printf("在10号位置加入两个元素之后\n");
	for (i = 0; i < list_length(&L); i++)
	{
		list_get(&L, i, &element);
		printf("线性表中的数据%d为:%d\n",i, element);
	}
	list_delete(&L, &element, 0);
	list_delete(&L, &element, 0);
	printf("在0号位置删除两个元素之后\n");
	for (i = 0; i < list_length(&L); i++)
	{
		list_get(&L, i, &element);
		printf("线性表中的数据%d为:%d\n",i, element);
	}
	system("pause");
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值