我正试图从排序的单链表中删除重复的值。
这是我的代码
SinglyLinkedListNode*删除重复项(SinglyLinked ListNode*头({
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;
}
然而,当Singly链表为3->3->3->4->5->5->空
请尝试此代码-
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;
}
}
}