1. 问题一
-
如何判断某个数据元素是否存在于线性表中?
-
查找一个元素是否存在线性表中,每次查找都是使用 for 循环,因此,我们需要封装一个 find 成员函数
-
可以为线性表(List)添加一个查找操作
// 参数:
// 带查找的数据元素
// 返回值:
// >= 0:数据元素再线性表中第一次出现的位置
// -1:数据元素不存在
int find(const T& e) const;
#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. 问题二
#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;
}
3. 分析
3.1 时间复杂度对比分析
- 顺序表的整体时间复杂度比单链表要低,那么单链表还有使用价值吗?
3.2 效率的深度分析
- 实际工程开发中,时间复杂度只是效率的一个参考指标
- 对于内置基础类型,顺序表和单链表的效率不相上下
- 对于自定义类型,顺序表在效率上低于单链表
3.2.1 插入和删除
- 顺序表:设计大量数据对象的赋值操作
- 单链表:只涉及指针操作,效率与数据对象无关
3.2.2 数据访问
- 顺序表:随机访问,可直接定位数据对象
- 单链表:顺序访问,必须从头访问数据对象,无法直接定位
3.2.3 工程开发中的选择
- 顺序表
- 数据元素的类型相对简单,不涉及深拷贝
- 数据元素相对稳定,访问操作远多于插入删除操作
- 单链表
- 数据元素的类型相对复杂,复制操作相对耗时
- 数据元素不稳定,需要经常插入和删除,访问操作较少