C++ - 单链表 - 想法
我想编写一种方法来从单链表中删除具有重复数据值的连续项。该方法应返回删除的项目数。该方法应该根据需要清理内存,并且应该假设内存是使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
std::list
,在将元素推入其上之前,您必须检查:You can use
std::list
, and before pushing element on it you must check:在元语言中:
in meta language:
据我所知,这里没有太多需要优化的地方。返回使用的项目数只是递增计数器的一种情况。基本上,如果您发现 litem->data == litem->next->data,那么您需要像这样进行删除:
继续迭代直到 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:
Keep iterating until currentItem->next == NULL, to avoid referencing beyond the end of the list.