删除链表重复结点,重复结点不保留
Posted 你快看看我
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了删除链表重复结点,重复结点不保留相关的知识,希望对你有一定的参考价值。
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
先定义三个结点:
struct ListNode* prev=NULL;
struct ListNode* cur=phead;
struct ListNode* next=phead->next;
当cur和next不相等时,prev,cur ,next都向前走一步,知道cur和next相等时,prev,cur不动,next往前走,知道cur,next不等时,next停止前进。此时cur走到next的位置,next走到next的下一次位置,删除此时prev和cur之间的全部结点,连接prev和cur之间被断开的链表,图解如图所示:
struct ListNode* deleteDuplication(struct ListNode* pHead)
if (pHead == NULL || pHead->next == NULL)
return pHead;
//起始条件
struct ListNode* prev = NULL;
struct ListNode* cur = pHead;
struct ListNode* next = pHead->next;
while (next)
if (cur->val == next->val)
//删除重复结点
while (next && cur->val == next->val)//next往后走,找到和cur不相等的地方
next = next->next;
//删掉cur到next之间
while (cur != next)
struct ListNode* del = cur;
cur = cur->next;
free(del);
if (prev == NULL)
pHead = cur;
else
prev->next = cur;
if (next)
next = next->next;
else
prev = cur;
cur = next;
next = next->next;
return pHead;
代码已经解决了一些比较特殊的情况,比如如果一组数全是重复的数字的情况,或者链表为空或者链表只有一个结点的情况,还有可能前几个是重复的,此时prev为空的情况,这些问题还需要读者特别注意。
以上是关于删除链表重复结点,重复结点不保留的主要内容,如果未能解决你的问题,请参考以下文章