0

我正在编写一个删除具有重复数据的连续项目的函数。eg 例如,传入列表

->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);  
 }
}

这是实现预期结果的正确方法吗?

4

5 回答 5

2

I don't see current being incremented to current->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(current->next != NULL) {
   if ( current->data == current->next->data) {
     // delete duplicates .
   } else {
     current = current -> next;
   }
}// end-while
return (count);
于 2010-10-22T13:47:10.613 回答
2

You need to add an else inside the while loop to advance to the next node:

if( current-> data == current->next->data ) {
....
} else {
    current = current->next;
}

Also the returns need to be fixed (the first should return 0 and the second should be moved outside the while loop).

于 2010-10-22T13:48:16.860 回答
1

一些快速观察:

return (count)语句可能在while循环之外,否则循环将过早终止。

循环current = current->next;内需要类似的语句。while否则,循环将成为无限循环。

于 2010-10-22T13:53:54.377 回答
1
  1. 如果没有重复匹配,当前应该移动到 current->next。
  2. 传递给函数的参数应该只是 *list(即指向 struct litem 类型元素的指针)
  3. 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);  
}
于 2010-10-22T13:53:18.713 回答
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);
 }
于 2010-10-22T13:54:59.170 回答