从排序的单链列表中删除重复值

问题描述

我正在尝试从排序的单链列表中删除重复的值。

这是我的代码

SinglyLinkedListNode * removeDuplicates(SinglyLinkedListNode *头) {

if(head==NULL)
     return head;

  int flag=0;
  SinglyLinkedListNode* p,*q,*temp;

  for(p=head;p->next!=NULL;p=p->next)
      {
          if(flag==1)
             {
                 p=temp;
                 flag=0;
             }

          q=p->next;

          if(q->data==p->data)
             {
                 temp=p;
                 p->next=q->next;
                 free(q);
                 flag=1;
             }
      }

      return head;

}

但是,当单链接列表为3-> 3-> 3-> 4-> 5-> 5-> 5-> NULL时,代码将失败

解决方法

请尝试使用此代码-

void removeDuplicates(SinglyLinkedListNode* head)  
{  
    SinglyLinkedListNode* current = head;  
  
    SinglyLinkedListNode* nextNode;  
      
    if (current == NULL)
    return;  
  
    while (current->next != NULL)  
    {  
    if (current->data == current->next->data)  
    {       
        nextNode = current->next->next;  
        free(current->next);  
        current->next = nextNode;
    }  
    else
    {  
        current = current->next;  
    }  
    }  
}