23 - 顺序表和单链表的对比分析

1. 问题一

  • 如何判断某个数据元素是否存在于线性表中?

  • 查找一个元素是否存在线性表中,每次查找都是使用 for 循环,因此,我们需要封装一个 find 成员函数

  • 可以为线性表(List)添加一个查找操作

// 参数:
// 带查找的数据元素
// 返回值:
// >= 0:数据元素再线性表中第一次出现的位置
// -1:数据元素不存在
int find(const T& e) const;

【23 顺序表和单链表的对比分析】

#include <iostream>
#include "LinkList.h"

using namespace DTLib;
using namespace std;

int main()
{
    LinkList<int> list;

    for (int i = 0; i < 5; i++)
    {
        list.insert(0, i);
    }

    cout << list.find(0) << endl;

    return 0;
}

在这里插入图片描述

2. 问题二

【23 顺序表和单链表的对比分析】

#include <iostream>
#include "LinkList.h"

using namespace DTLib;
using namespace std;

// int main()
// {
//     LinkList<int> list;

//     for (int i = 0; i < 5; i++)
//     {
//         list.insert(0, i);
//     }

//     cout << list.find(0) << endl;

//     return 0;
// }

class Test : public Object
{
    int i;
public:
    Test(int v = 0)
    {
        i = v;
    }
};

int main()
{
    Test t1(1);
    Test t2(2);
    Test t3(3);

    LinkList<Test> list;
    list.insert(t1);
    list.insert(t2);
    list.insert(t3);

    cout << list.find(t3) << endl;
}

在这里插入图片描述

如果是自定义类类型,则需要在顶层父类 Object 中重载==!=操作符。让我们自定义的类继承于 Object 类。

#include <iostream>
#include "LinkList.h"

using namespace DTLib;
using namespace std;

class Test : public Object
{
    int i;
public:
    Test(int v = 0)
    {
        i = v;
    }
    bool operator==(const Test& obj)
    {
        return (i == obj.i);
    }
};

int main()
{
    Test t1(1);
    Test t2(2);
    Test t3(3);

    LinkList<Test> list;
    list.insert(t1);
    list.insert(t2);
    list.insert(t3);

    cout << list.find(t3) << endl;

    return 0;
}

在这里插入图片描述
【23 顺序表和单链表的对比分析_重载】

3. 分析

3.1 时间复杂度对比分析

在这里插入图片描述

  • 顺序表的整体时间复杂度比单链表要低,那么单链表还有使用价值吗?

3.2 效率的深度分析

  • 实际工程开发中,时间复杂度只是效率的一个参考指标
    • 对于内置基础类型,顺序表和单链表的效率不相上下
    • 对于自定义类型,顺序表在效率上低于单链表

3.2.1 插入和删除

- 顺序表:设计大量数据对象的赋值操作
- 单链表:只涉及指针操作,效率与数据对象无关

3.2.2 数据访问

- 顺序表:随机访问,可直接定位数据对象
- 单链表:顺序访问,必须从头访问数据对象,无法直接定位

3.2.3 工程开发中的选择

  • 顺序表
    • 数据元素的类型相对简单,不涉及深拷贝
    • 数据元素相对稳定,访问操作远多于插入删除操作
  • 单链表
    • 数据元素的类型相对复杂,复制操作相对耗时
    • 数据元素不稳定,需要经常插入和删除,访问操作较少
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uuxiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值