手写简单线性表

本文介绍了如何使用C++自建线性表,并详细阐述了实现插入、删除和查找等基本功能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值