This is my accepted solution.

```
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *p;
while (p) {
if (p->next && p->val == p->next->val) {
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
};
```

However if I try to free the memory of duplicate node, I get a Runtime error.

```
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *p, *q;
while (p) {
if (p->next && p->val == p->next->val) {
q = p->next;
p->next = p->next->next;
free(q); // free old p->next
}
else
p = p->next;
}
return head;
}
};
```

Could anyone explain why this happened? Thanks.