题目:见下图
答案:见下图
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head==NULL||head->next==NULL)
{
return head;
}
ListNode* prev=NULL;
ListNode* cur=head;
ListNode* next=cur->next;
while(next)
{
if(cur->val != next->val)
{
prev=cur;
cur=next;
next=next->next;
}
else
{
while(next&&next->val==cur->val)
{
next=next->next;
}
if(prev)
{
prev->next=next;
}
else
{
head=next;
}
while(cur!=next)
{
ListNode* del=cur;
cur=cur->next;
free(del);
}
if(next)
next=cur->next;
}
}
return head;
}
解析:
(1)返回当链表为空或者为一个的情况
if(head==NULL||head->next==NULL)
{
return head;
}
定义前,现在,下一个的指针
ListNode* prev=NULL;
ListNode* cur=head;
ListNode* next=cur->next;
(2)判断cur的值和next的值是否相同
第一种情况如果不相同,那么我们让prev,cur,next的指针分别向后一格
if(cur->val != next->val)
{
prev=cur;
cur=next;
next=next->next;
}
当相同时让next=next->next,
else
{
while(next&&next->val==cur->val)
{
next=next->next;
}
特殊情况,当开头就为1,1,2,3这种需要删除两个头节点的情况,我们则采用if-else语句来进行求解,当prev不为空让prev的->next指向next,否则则为上述文字的情况1,1,2,3此时prev为空,直接将next指针给与head当作头结点
if(prev)
{
prev->next=next;
}
else
{
head=next;
}
(3)使用free()函数释放重复结点
定义指针使其等于cur的值,使cur向后走,释放del指针
while(cur!=next)
{
ListNode* del=cur;
cur=cur->next;
free(del);
}
注意当需要删除的是最后的两个尾节点,如上图cur也会跟随next成为空,那么NULL->next=NULL,会出现语法错误,故我们采用if语句进行判断
if(next)
next=cur->next;
}
(4)返回头节点
return head;
到这里我们解题完毕
如果对您有帮助的话点一个免费的赞和收藏叭!