删除具有重复数据的项目
我正在编写一个函数来删除具有重复数据的连续项目。 例如 例如传入列表
->a->b->c->c->a->b->b->b->a->null
应该导致
->a->b->c->a->b->a->null
下面给出了列表项定义和函数声明
struct litem {
char data;
litem* next;
};
Mo 代码如下所示
int remove_dumplicates(litem *&list)
{
int count = 0;
struct litem * current = NULL;
current = list;
struct litem *deleteNode;
if (current == NULL ) return;
while(current->next != NULL)
{
if ( current->data == current->next->data) // check for the duplicates
{
count++;
deleteNode =current->next;
current>next= current->next->next;
delete deleteNode;
}
return (count);
}
}
这是实现以下功能的正确方法吗想要的结果?
I'm writing a function that removes the consecutive items with duplicate data .
e.g
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
The list item definition and function declaration are given below
struct litem {
char data;
litem* next;
};
Mo code looks like
int remove_dumplicates(litem *&list)
{
int count = 0;
struct litem * current = NULL;
current = list;
struct litem *deleteNode;
if (current == NULL ) return;
while(current->next != NULL)
{
if ( current->data == current->next->data) // check for the duplicates
{
count++;
deleteNode =current->next;
current>next= current->next->next;
delete deleteNode;
}
return (count);
}
}
Is this a correct way of achieving the desired result ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我没有看到
current
增加到current->next
。以包含所有唯一元素
a ->; 的列表为例。 b-> c
并查看您的程序如何工作。要解决此问题,您需要:
I don't see
current
being incremented tocurrent->next
.Take as an example a list with all unique elements
a -> b -> c
and see how your program works.To fix this you need:
您需要在 while 循环内添加 else 以前进到下一个节点:
还需要修复返回值(第一个应返回 0,第二个应移至 while 循环之外)。
You need to add an else inside the while loop to advance to the next node:
Also the returns need to be fixed (the first should return 0 and the second should be moved outside the while loop).
一些快速观察:
return (count)
语句可能位于while
循环之外,否则循环将提前终止。while
循环内需要像current = current->next;
这样的语句。否则,循环将变成无限循环。Some quick observations:
The
return (count)
statement might be outside thewhile
loop, otherwise the loop would be terminated prematurely.A statement like
current = current->next;
is required inside thewhile
loop. Otherwise, the loop would become an infinite loop.delete
是一个 C++ 关键字。请改用free()
。修改后的代码:
delete
is a C++ keyword. Usefree()
instead.The modified code:
试试这个:
Try this: