【问题标题】:Check if data is already in list检查数据是否已经在列表中
【发布时间】:2014-02-04 22:55:08
【问题描述】:

我正在处理一个链表项目,我有两个无法正常工作的功能。

首先我有一个插入函数,可以将元素添加到列表中。但是该函数首先要检查元素是否已经在列表中。它应该通过使用 bool 函数 contains() 来做到这一点。如果元素已经在列表中,那应该返回 true

我的插入函数:

void StringSet::insert(string element)
{
    NodePtr temp =head;
    if (contains("element") == true)
    {
        return;
    }
    if(head == NULL)
    {
        head = new StringNode;
        head->setData(element);
        head->setLink(NULL);
    }
    else
    {
        temp = new StringNode;
        temp->setData(element);
        temp->setLink(head);
        head = temp;
    }

}

还有我的包含功能:

bool StringSet::contains(string element)
{
      NodePtr temp = head;

    while(temp != NULL)
    {
        if (temp->getData() == element)
        {
            cout<<"This country has already been registered!"<<endl;
            return true;
        }

        temp = temp->getLink();
    }


}

【问题讨论】:

  • getLink() 是如何定义的? contains 看起来不错(除了它缺少 return false
  • contains("element")contains(element) 大不相同。

标签: c++ linked-list


【解决方案1】:

您在方法调用中使用的是文字而不是变量:

if (contains("element") == true)

应该是:

if (contains(element) == true)

【讨论】:

  • 啊,难以置信。花了 30 分钟盯着它看,可能改变了其他一切:)。但是现在可以了,谢谢! :)
  • @user3265963 这可能发生在最优秀的程序员身上。
【解决方案2】:

函数 contains 具有未定义的行为,因为如果列表中没有目标元素,它不会返回任何内容。改成如下方式

bool StringSet::contains( const string &element ) const
{
    NodePtr temp = head;

    while( temp != NULL && temp->getData() != element ) temp = temp->getLink();

    return ( temp != NULL );
}

并改变它的调用

if (contains("element") == true)

if ( contains( element) )

因为“元素”与元素不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2015-07-12
    • 1970-01-01
    • 2021-06-13
    • 2013-01-18
    • 2011-04-23
    相关资源
    最近更新 更多