C++ - 单链表 - 想法

发布于 2024-09-07 22:07:20 字数 588 浏览 2 评论 0原文

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

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

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

struct litem { 字符数据; 下一个项目*; };

int remove_consecutive_duplicates(item*&列表);

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..

I want to write a method to remove consecutive items with duplicate data values from a singly linked list. The method should return the number of items removed. The method should clean up memory as required, and should assume that memory was allocated using new.

For example, passing in the list
->a->b->c->c->a->b->b->b->a->null
should result in
->a->b->c->a->b->a->null
and return 3

The list item definition and function declaration are given below

struct litem {
char data;
litem* next;
};

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..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野の 2024-09-14 22:07:20

您可以使用 std::list,在将元素推入其上之前,您必须检查:

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

l.push_back(next);

You can use std::list, and before pushing element on it you must check:

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

l.push_back(next);
病女 2024-09-14 22:07:20

在元语言中:

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
}

in meta language:

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
}
鱼窥荷 2024-09-14 22:07:20

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

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

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

As far as I can see, there's not a lot to optimize here. Returning the number of items used is just a case of incrementing a counter. Basically, if you find that litem->data == litem->next->data, then you need to do the removal like so:

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

Keep iterating until currentItem->next == NULL, to avoid referencing beyond the end of the list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文