存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中?没有重复出现?的数字。
返回同样按升序排列的结果链表。
示例 1:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3]
输出:[2,3]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if(head == NULL || head->next == NULL)
return head;
struct ListNode* prev = NULL;
struct ListNode* cur = head;
struct ListNode* next = cur->next;
while(next)
{
if(cur ->val != next->val)
{
prev = cur;
cur = next;
next = next->next;
}
else
{
while(next &&cur->val == next->val)
{
next = next->next;
}
if(prev)
{
prev->next = next;
}
else
{
head = next;
}
while(cur != next)
{
struct ListNode*del = cur;
cur = cur->next;
free(del);
}
if(next)
next = cur->next;
}
}
return head;
}
|