我正在尝试从已排序的单向链表中删除重复值。
这是我的代码
SinglyLinkedListNode* removeDuplicates(单链接列表节点*头){
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时,代码会失败
发布于 2020-08-30 01:54:54
请尝试这个代码-
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;
}
}
}https://stackoverflow.com/questions/63649512
复制相似问题