我正在编写一个删除具有重复数据的连续项的函数。 例如 例如,传入列表
- > A-> B-> C-> C-> A-> B-> B-> B-> A->空
应该导致
- > A-> B-> C-> A-> B-> A->空
列表项定义和函数声明如下所示
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);
}
}
这是达到预期效果的正确方法吗?
答案 0 :(得分:2)
我没有看到current
增加到current->next
。
以包含所有唯一元素a -> b -> c
的列表为例,了解您的程序的工作原理。
要解决此问题,您需要:
while(current->next != NULL) {
if ( current->data == current->next->data) {
// delete duplicates .
} else {
current = current -> next;
}
}// end-while
return (count);
答案 1 :(得分:2)
您需要在while循环中添加else以前进到下一个节点:
if( current-> data == current->next->data ) {
....
} else {
current = current->next;
}
还需要修复返回值(第一个应返回0,第二个应移到while循环之外)。
答案 2 :(得分:1)
delete
是一个C ++关键字。请改用free()
。修改后的代码:
int remove_duplicates(struct 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)
{
count++;
deleteNode = current->next;
current->next= current->next->next;
free(deleteNode);
}
else
{
current = current->next;
}
}
return (count);
}
答案 3 :(得分:1)
一些快速观察:
return (count)
语句可能在while
循环之外,否则循环将提前终止。
current = current->next;
循环中需要while
之类的语句。否则,循环将变为无限循环。
答案 4 :(得分:0)
试试这个:
int remove_duplicates(litem *&list)
{
int count = 0;
struct litem * current = NULL;
current = list;
struct litem *deleteNode;
if (current == NULL ) return 0;
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;
}
else
{
current = current->next;
}
}
return (count);
}