C++自建List
线性表应具有最基本的插入、删除、查找功能
/*
Author: XT
Date: 2020-9-8
Topic: 顺序表基本操作
*/
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
#define MAX 10000
//定义一个int类型线性表
struct List {
int L[MAX], Length;
};
//线性表初始化
void Initalize(List& ScList)
{
memset(ScList.L, 0, sizeof(ScList.L)); //初始化线性表中L
ScList.Length = 0;
}
//返回线性表长度
int Cal_Length(List ScList)
{
return ScList.Length;
}
//插入线性表元素
void InsertList(List& ScList, int IP, int x)
{
if (IP > ScList.Length + 1 || IP < 1 || IP >= MAX) { //如果超过线性表最大长度MAX或者超过当前地址范围报错
printf("请输入正确地址\n");
return;
}
for (int i = ScList.Length; i >= IP; i--)
ScList.L[i + 1] = ScList.L[i];
ScList.L[IP] = x;
ScList.Length++;
}
//删除线性表中某位置元素
void Delete(List& ScList, int IP)
{
if (IP > ScList.Length + 1 || IP < 1 || IP >= MAX) { //如果超过线性表最大长度MAX或者超过当前地址范围报错
printf("请输入正确地址\n");
return;
}
for (int i = IP; i <= ScList.Length; i++)
ScList.L[i] = ScList.L[i + 1];
ScList.L[ScList.Length] = 0;
ScList.Length--;
}
//查询线性表中某元素位置
int Find(List ScList, int x)
{
for (int i = 1; i <= ScList.Length; i++)
if (ScList.L[i] == x)
return i;
printf("未找到元素,请重新尝试!\n");
return 0;
}
//查找某位置的元素值
int Findip(List ScList, int ip)
{
if (ip < 1 || ip > ScList.Length) {
printf("未找到正确地址,请重新尝试!\n");
return 0;
}
return ScList.L[ip];
}
//显示顺序表中的数据
void Show(List ScList)
{
for (int i = 1; i <= ScList.Length; i++)
printf("%d ", ScList.L[i]);
printf("\n");
}
int main()
{
List ScList;
int ip, x;
Initalize(ScList);
printf("当前线性表长度为:%d\n", Cal_Length(ScList));
printf("请输入插入元素的位置和大小:\n");
while (~scanf("%d %d", &ip, &x))
InsertList(ScList, ip, x);
printf("当前线性表长度为:%d\n", Cal_Length(ScList));
printf("请输入需要删除的元素的位置:\n");
while (~scanf("%d", &ip))
Delete(ScList, ip);
printf("当前线性表长度为:%d\n", Cal_Length(ScList));
printf("当前顺序表中元素为:\n");
Show(ScList);
printf("请输入需要查找的元素的大小:\n");
while (~scanf("%d", &x))
if (Find(ScList, x))
printf("%d\n", Find(ScList, x));
printf("请输入需要查找的元素的位置:\n");
while (~scanf("%d", &ip))
if (Findip(ScList, ip))
printf("%d\n", Findip(ScList, ip));
return 0;
}//有问题请联系e-mail:1416397544@qq.com