【问题标题】:Deleting duplicate values from a sorted singly linked list从已排序的单链表中删除重复值
【发布时间】:2020-08-29 16:48:59
【问题描述】:

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

这是我的代码

SinglyLinkedListNode* removeDuplicates(SinglyLinkedListNode* head) {

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->NULL 时代码失败

【问题讨论】:

    标签: data-structures linked-list singly-linked-list


    【解决方案1】:

    请试试这个代码-

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 2013-04-28
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多