码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-03 00:22:51      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:对比分析   返回   没有   基本   nbsp   bool   继承   else   判断   

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

for(int i=0; i<list.length(); i++)
{
    if(list.get(i) == v)
    {
        cout << "find it" <<endl;
    }
}

遗失的操作——find
-可以为线性表(List)增加一个查找操作
-int find(const T& e) const;

  参数:
  待查找的数据元素
  返回值:
  >=0: 数据元素在线性表中第一次出现的位置
  -1:数据元素不存在

在List.h中新增一个纯虚函数:

virtual int find(const T& e) const = 0;

因为LinkList.h和SeqList.h是List.h的子类,因此需要在LinkList.h和SeqList.h中将find纯虚函数实现:

LinkList.h

int find(const T& e)const
    {
        int ret = -1;
        int i=0;
        Node* node = m_header.next;
        while(node)
        {
            if(node->value == e)
            {
                ret = i;
                break;
            }
            else
            {
                node = node->next;
                i++;
            }
        }

        return ret;
    }

SeqList.h

 int find(const T& e) const
    {
        int ret = -1;
        for(int i=0; i<m_length; i++)
        {
            if(m_array[i] == v)
            {
                ret = i;
                break;
            }
        }
        return ret;
    }

测试:

(1)基本类型的测试

LinkList<int> list;

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

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

基本类型的测试是OK的

(2)自定义类类型的测试

在main.cpp中添加下面的代码:

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

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

    LinkList<Test> list;


    return 0;

}

进行编译,会出现如下错误:

技术图片

比较两个Test对象是否相等,并没有重载相等操作符。

暂且做一件没有意义的事,只是让代码编译过去。

class Test
{
int i;
public:
    Test(int v=0)
    {
        i = v;
    }
    bool operator == (const Test& e)
    {
        return true;
    }
};

这样虽然可以编译通过,但是这样做不好,不值得推荐。

我们可以在顶层的父类中实现相等和不相等操作符的重载函数

Object.h

  bool operator == (const Object& obj);
  bool operator != (const Object& obj);

Object.cpp

bool Object::operator ==(const Object& obj)
{
    return (this == &obj);  //比较地址是最好的选择
}

bool Object::operator !=(const Object& obj)
{
    return (this != &obj);
}

在main.cpp中:

class Test : public Object  //将自定义类继承于Object,是为了避免编译错误。
{
int i;
public:
    Test(int v=0)
    {
        i = v;
    }

    bool operator ==(const Test& e)  //判断两个对象的依据是判断对象的成员变量i是否相等,需要重新实现operator ==()函数
    {
        return (i == e.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(t2) <<endl;


    return 0;

}

 

技术图片

从这个表中可以看出,单链表的时间复杂度相比顺序表没有什么优势,反而更差,那么忙工程中为什么单链表会使用的比较多呢?

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

技术图片

 

 技术图片

 

 技术图片

 

 技术图片

 

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

标签:对比分析   返回   没有   基本   nbsp   bool   继承   else   判断   

原文地址:https://www.cnblogs.com/-glb/p/12142785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!