如何实现布尔表达式以查找链表中的重复项?

时间:2015-07-09 20:12:58

标签: c++ duplicates nodes singly-linked-list

我遇到了我的函数问题,如果链表有一个传递给函数的特定值的副本,则假设返回true

注意:这是一个单链表。

3 个答案:

答案 0 :(得分:1)

您可能正在->getNext项目上调用NULL。您希望while检查以下解决方案:

while (nodeptr != NULL)

答案 1 :(得分:0)

除了while语句的条件应该是

while ( nodeptr != NULL )

我没有看到该功能的其他问题。

然而,我会按以下方式定义

bool List<Object>::hasDuplicates( const Object& data ) const
{
    // Determine whether the data element is duplicated

    size_type counter = 0;

    for ( ListNode<Object>* nodeptr = head; counter < 2 && nodeptr; nodeptr = nodeptr->getNext() )
    {   
        if ( nodeptr->getElement() == data ) ++counter;
    }

    return counter == 2;
}

编写循环的另一种方法是使用break语句。例如

bool List<Object>::hasDuplicates( const Object& data ) const
{
    // Determine whether the data element is duplicated

    size_type counter = 0;

    for ( ListNode<Object>* nodeptr = head; nodeptr; nodeptr = nodeptr->getNext() )
    {   
        if ( nodeptr->getElement() == data && ++counter == 2 ) break;
    }

    return counter == 2;
}

答案 2 :(得分:0)

递归爱好者可能会建议:

// returns true when data contained in list more than once
// else returns false
template <class Object>
bool List<Object>::hasDuplicates( const Object& data ) const
{
   ListNode<Object>* head = front();  // gotta start some where

   int counter = 0;
   if(head != nullptr)  // list not empty?
      head->hasDuplicates (data, counter); // recursive search

  return (count > 1);
}

// recursive - counter incremented when data matches element
//             aborts further search when counter > 1
template <class Object>
void List<Object>::hasDuplicates( const Object& data, int& counter ) const
{
   counter += (data == getElement()) ? 1 : 0; // is node dup 

   if(counter > 1) return;           // found 2nd, abort search

   if(nullptr == getNext()) return; // abort search, no more elements

   getNext()->hasDuplicates(data, counter);  // tail recursion
}

未编译..仅用于说明目的。

带有-O3的g ++对尾递归的处理给我留下了深刻的印象

相关问题