【问题标题】:C++ - Single Linked List - IdeasC++ - 单链表 - 想法
【发布时间】:2011-03-11 10:12:34
【问题描述】:

我想编写一个方法来从单链表中删除具有重复数据值的连续项目。该方法应返回删除的项目数。该方法应根据需要清理内存,并应假定内存是使用 new 分配的。

例如传入列表
->a->b->c->c->a->b->b->b->a->null 应该导致
->a->b->c->a->b->a->null 并返回 3

列表项定义和函数声明如下

结构项目{ 字符数据; 莱姆*下一个; };

int remove_consecutive_duplicates(litem*& list);

I have a simple logic to check the next element recursively & removing the element if its duplicate. 
But, i would like to know how many efficient ways to do this ?  All ideas welcome from C++ gurus..

【问题讨论】:

  • 如果是作业,你可以这样标记它
  • 您不必成为 C++ 大师 也可以完成作业。而且您也不必递归地 ;)
  • 您需要意识到的是,如果您必须遍历容器中的所有元素,那么最有效的方法总是O(n)。您绝对可以编写递归算法以在 O(n) 中求解,但您可能不需要,至少在这种情况下(此外,在效率方面很容易将递归算法搞砸)。简单地遍历列表将为您提供所需的输出。

标签: c++ stl linked-list


【解决方案1】:

元语言:

item = items.first
while (item != null) {
    while (item.next != null && item.value = item.next.value) {
        temp = item.next
        item.next = item.next.next
        temp.dispose
    }
    item = item.next
}

【讨论】:

    【解决方案2】:

    据我所知,这里没有太多需要优化的地方。返回使用的项目数只是增加计数器的一种情况。基本上,如果您发现 litem->data == litem->next->data,那么您需要像这样进行删除:

    litem* tmpItem = currentItem->next;
    currentItem->next = tmpItem->next;
    delete tmpItem;
    

    继续迭代直到 currentItem->next == NULL,以避免引用超出列表末尾。

    【讨论】:

      【解决方案3】:

      你可以使用std::list,在推送元素之前你必须检查:

      if ((*l.rbegin()) == next)
      {
          return;
      }
      
      l.push_back(next);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-02
        • 2020-07-01
        • 2013-12-03
        相关资源
        最近更新 更多