题目描述
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中没有重复出现的数字。返回同样按升序排列的结果链表。
示例
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
解题思路
因为是已排序链表,所以重复元素一定是连续出现的,我们可以以相邻的元素是否相等作为其是否为重复元素的判断依据。
具体做法为,使用指针cur指向链表的头节点,随后开始遍历链表,如果当前节点与下一个节点对应的元素相同,那么则删除当前节点及后面所有拥有相同元素的节点。直到遍历完成。需要注意的是,头节点也可能被删除,所以需要一个前置节点cur,cur->next指向头节点,然后开始遍历。
解题代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if (NULL == head)
{
return NULL;
}
struct ListNode dummy;
dummy.next = head;
struct ListNode* cur = &dummy;
while (cur->next != NULL && cur->next->next != NULL)
{
if (cur->next->val == cur->next->next->val) // 重复元素
{
int tmp = cur->next->val;
while (cur->next != NULL && cur->next->val == tmp) // 删除cur->next及其后面全部相同元素的节点
{
/*
* 注意此处不要只简单的做指针偏移,需要实际删除对应节点
* 不free对应节点会导致内存泄漏
*
* cur->next = cur->next->next; 为不严谨解法
*/
struct ListNode* p = cur->next;
cur->next = p->next;
free(p);
}
}
else // 非重复元素,继续遍历
{
cur = cur->next;
}
}
return dummy.next;
}