# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
solve.c

## Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example, Given `1->2->3->3->4->4->5`, return `1->2->5`. Given `1->1->1->2->3`, return `2->3`.

## Solution

• `q->val != p->val`, 则直接更新p，pre
```pre = p;
p = p->next;```
• 否则指向删除q，直到q与p值不相等
```while(q && q->val == p->val) {
p->next = p->next->next;
free(q);
q = p->next;
}```

• `p == head`, 即头节点就出现重复，需要更新head指针，并释放p
```head = p->next;
free(p);
• `p != head`, 则只需要删除p节点即可，利用pre指针
```pre->next = pre->next->next;
free(p);
p = q;```

## Code

```struct ListNode* deleteDuplicates(struct ListNode *head)
{
struct ListNode *p = head, *pre = NULL;
while (p) {
struct ListNode *q = p->next; // q is the next node of p
bool isDup = false;
while (q && q->val == p->val) {
isDup = true;
// delete q
p->next = p->next->next;
free(q);
// update q
q = p->next;
}
if (isDup) {
free(p);
} else {
pre->next = pre->next->next;
free(p);
p = q;
}
} else {
pre = p;
p = p->next;;
}
}