[数据结构]第三周作业

实现顺序表数据结构,并实现以下操作:初始化、释放、遍历(打印所有元素)、查找、插入、删除等。并在main函数中进行调用测试。

1.C语言实现顺序表操作

#include<stdio.h>
#define MAXSIZE 100

typedef int ElemType;

typedef struct
{
	ElemType data[MAXSIZE];
	int length;
}SqList;

// 初始化
void InitList(SqList* L)
{
	L->length = 0;
}

// 释放
void DestroyList(SqList* L)
{
	L->length = 0;
}

// 遍历打印
void ErgodicList(SqList* L)
{
	for (int i = 0; i < L->length; i++)
	{
		printf("%d ", L->data[i]);
		printf(" ");
	}
	printf("\n");
}

// 查找,返回元素下标
int LocateElem(SqList* L, ElemType e)
{
	for (int i = 0; i < L->length; i++)
	{
		if (L->data[i] == e)
		{
			return i;
		}
	}
	return -1; 
}

// 插入
void InsertList(SqList* L, int i, ElemType e)
{
	if (i < 0 || i > L->length) // i的合法范围为[0, L->length],不能插在0之前,也不能插在L->length之后
	{
		printf("位置不合法\n");
		return;
	}

	if (L->length >= MAXSIZE)
	{
		printf("表满\n");
		return;
	}

	for (int j = L->length; j > i; j--) // 从后往前,将第i个元素及其后面的元素后移
	{
		L->data[j] = L->data[j - 1];
	}
	L->data[i] = e;
	L->length++;
}

// 删除
ElemType DeleteList(SqList* L, int i,ElemType e)
{
	if (i < 0 || i >= L->length) // i的合法范围为[0, L->length)
	{
		printf("位置不合法\n");
		return e;
	}

	e=L->data[i];

	for (int j = i; j < L->length - 1; j++) // 从前往后,将第i个元素及其后面的元素前移
	{
		L->data[j] = L->data[j + 1];
	}
	L->length--;

	return e;
}

2.运行

//实现顺序表数据结构,并实现以下操作:初始化、释放、遍历(打印所有元素)、查找、插入、删除等。并在main函数中进行调用测试。
#include<iostream>
#include<fstream>
#include<string>
#include"Operations.c"
using namespace std;

int main()
{
	SqList L;
	InitList(&L);
	int n;
	cout<<"输入元素个数:";
	cin>> n;

	// 初始化
	for (int i = 0; i < n; i++)
	{
		int e;
		cout<<"输入第"<<i+1<<"个元素:";
		cin>>e;
		InsertList(&L,i,e);
	}

	// 遍历打印
	ErgodicList(&L);

	// 查找
	int e;
	cout<<"输入要查找的元素:";
	cin>>e;
	int index = LocateElem(&L,e);
	if (index == -1)
	{
		cout<<"未找到"<<endl;
	}
	else
	{
		cout<<"元素"<<e<<"的下标为"<<index<<endl;
	}

	// 插入
	int i;
	cout<<"输入要插入的位置下标:";
	cin>>i;
	cout<<"输入要插入的元素:";
	cin>>e;
	InsertList(&L,i,e);
	cout<<"插入后:";
	ErgodicList(&L);

	// 删除
	cout<<"输入要删除的元素的位置下标:";
	cin>>i;
	DeleteList(&L,i,e);
	cout<<"删除后:";
	ErgodicList(&L);

	// 释放
	DestroyList(&L);
	cout<<"释放后:";
	ErgodicList(&L);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值