数据结构中顺序表的相关操作

功能说明

代码为顺序表的相关操作,主要操作为初始化、插入元素、查找元素、删除元素、计算表长、获取表中元素位置以及打印顺序表等功能。代码由头文件(SqList.h)、接口实现(SqList.c)和测试文件(main.c)三部分组成。
SqList.h

#ifndef __SqList__
#define __SqList__
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#pragma warning(disable:4996)
typedef int ElementType;
#define Maxsize 100
typedef struct LNode
{
	ElementType Data[Maxsize];
	ElementType  length;
}SqList;
#define OK 1
#define ERROR 0
typedef int Status;
//SqList *Init();
void Init(SqList* L);
Status Insert(SqList *L, int i, ElementType x);
Status Find(SqList L, ElementType x);
Status Delete(SqList *L, int i);
int Length(SqList L);
Status print(SqList L);
Status GetElem(SqList L, int i, ElementType *e);
#endif

SqList.c

#include "SqList.h"
//判断顺序表是否为空
//SqList* Init()
//{
//	SqList * L = NULL;
//	L = (SqList*)malloc(sizeof(struct LNode));
//	L->length =0;
//	memset(L->Data, 0, sizeof(L->Data));
//	return L;
//}
void Init(SqList *L)
{
	L->length = 0;
	memset(L->Data, 0, sizeof(L->Data));
	return;
}
//像顺序表中插入元素 i 表示插入的位置,x表示插入的元素
Status Insert(SqList *L, int i, ElementType x)
{
	int j;
	if (L->length ==Maxsize)
	{
		printf("表已装满!\n");
		return ERROR;
	}
	if (i < 1 || i >L->length + 1)
	{
		printf("插入的位置不合法!\n");
		return false;
	}
	for (j = L->length; j >= i; j--)
	{
		L->Data[j] = L->Data[j - 1];
	}
	L->Data[j] = x;
	L->length++;
	return OK;
}
Status Find(SqList L, ElementType x)
{
	int j;
	for (j = 0; j < L.length; j++)
	{
		if (x == L.Data[j])
		{
			printf("%d所在的位置为%d\n", x, j + 1);
			return OK;
		}
	}
	printf("查找的元素不存在!!\n");
	return ERROR;
}
//i表示删除的位置
Status Delete(SqList *L, int i)
{
	int j;
	if (L->length == 0)
	{
		printf("表已空!,无法删除");
	}
	if (i < 1 || i > L->length)
	{
		printf("位置不合法!\n");
		return ERROR;
	}
	for (j = i; j < L->length; j++)
	{
		L->Data[j - 1] = L->Data[j];
	}
	L->length--;
	return OK;
}
Status Length(SqList L)
{
	return L.length;
}
Status print(SqList L)
{
	if (L.length == 0)
	{
		return ERROR;
	}
	int i;
	for (i = 0; i < L.length; i++)
	{
		printf("%d ", L.Data[i]);
	}
	printf("\n");
	return OK;
}
Status GetElem(SqList L, int i, ElementType *e)
{
	if (L.length == 0 || i > L.length)
		return ERROR;
	*e = L.Data[i - 1];
	return OK;
}

main.c

#include "SqList.h"
int main(int argc, const char* argv[])
{
	SqList L;
	Init(&L);
	Insert(&L, 1, 1);
	Insert(&L, 2, 2);
	Insert(&L, 3, 3);
	Insert(&L, 4, 4);
	Insert(&L, 5, 5);
	print(L);
	Find(L, 4);
	Delete(&L, 2);
	print(L);
	printf("表长为%d\n", Length(L));
	system("pause");
	return 0;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值