实现顺序表数据结构,并实现以下操作:初始化、释放、遍历(打印所有元素)、查找、插入、删除等。并在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;
}