我的问题是从链接列表中删除重复项。但我想在添加到链接列表之前完成。

struct myStr{int number; mystr *next;}
void append(mystr **q,int item)
{
myStr *temp;
temp = *q;
myStr *newone;
if(*q==NULL)// There should be control of previous elements. Call of keysearch function.
     {   temp = (myStr *)malloc(sizeof(myStr));

          temp->number =size;
          temp->next=NULL;
          *q=temp;
     }
     else //And also here
     {  temp = *q;
         while(temp->next !=NULL)
         {  temp=temp->next;
         }
         newone = (myStr *)malloc(sizeof(myStr));
         newone->count = size;
         newone->next=NULL;
         temp->next=newone;

     }
}
int keysearch (myStr *p)
{
struct myStr *temp = p;
int found = 0;
int key= p->number;
while (temp->next != NULL)
 {
 if(temp->number == key)
    {
   return 1;
//break;
        }
     temp = temp->next;
     }
    return 0;
    }

我的问题出在键盘搜索上。我不知道怎么了或者还有别的办法。

最佳答案

在您的代码中,有两条注释,您希望在其中调用keySearch事实上,你只需要把它放在一个地方——第二条评论。这是因为首先你要创建一个全新的列表,所以当然没有什么是你需要担心的。
在第二种情况下,您需要调用这个keySearch方法我认为有三种keySearch方法是有用的:
调用一个方法int keySearch(mystr *p, int value),该方法通过p查找value,如果找到,则返回true(非零数)
调用一个方法int keySearch(mystr *p),该方法通过p查找并删除所有重复项。不过,这不会在每个附加上调用,上面的实现表明这不是您要做的。无论如何,要做的工作要多得多。
调用一个方法来查看int keySearch(mystr *p)中的第一个值是否重复,如果重复则返回p。看来这就是你的方法要做的。
根据方法的签名,您尝试执行2或3。但这两种想法都是错误的——他们认为你已经将副本添加到了列表中。你应该做的是首先防止重复的内容被添加。不过,目前的方法没有足够的信息来完成这项工作。它需要尚未添加的元素的值。
我建议将方法更改为1中的方法,并传入要添加的值如果找到了,返回1。在q方法中,如果此函数的计算结果为1,则不追加任何内容。否则追加新元素。

int keysearch(struct myStr *p, int value)
{
   if(p == NULL) return 0;
   // reusing p is fine - it's a local variable
   while(p != NULL)
   {
      if(p->number == value) return 1;  // return if value exists already
      p = p->next;                      // go to next element
   }
   return 0;
}

现在,当您要添加一个元素时,首先用这个方法运行它如果该方法返回1,请立即保留true方法-无需执行任何操作如果返回0,则append新节点并将其设置到列表的末尾。
编辑:一个有进取心的程序员可能希望稍微优化一下,这样在每个append上我们就不会在整个列表中做两个循环(一个循环用于malloc,另一个循环用于查找实际追加的最后一个元素)。您可以通过稍微修改append来完成此操作。。。
// returns NULL if p is empty / value exists; otherwise returns the last element
struct myStr *keysearch(struct myStr *p, int value)
{
   // same logic, different return values; integration into append changes too!
}

07-24 09:45
查看更多