83. remove duplicates from sorted list

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
ListNode* (ListNode* head) {
if (head != NULL) {
ListNode *p = head;
while (p->next != NULL) {
int val = p->val;
if (val == p->next->val) {
ListNode *tmp = p->next;
p->next = p->next->next;
free(tmp);
} else {
p = p->next;
}
}
}
return head;
}
};