83 Remove Duplicates From Sorted List
83 Remove Duplicates From Sorted List
Remove Duplicates from Sorted List 
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
1
2
3
4
**Input:** head = [1,1,2]
**Output:** [1,2]
Example 2:
1
2
3
4
**Input:** head = [1,1,2,3,3]
**Output:** [1,2,3]
Constraints:
1
2
3
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be **sorted** in ascending order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL) {
return head;
}
struct ListNode* prev = head;
struct ListNode* tmp = head;
while (prev ->next != NULL && prev ->next -> next != NULL ) {
tmp = prev -> next;
if (prev -> val == tmp -> val) {
prev -> next = tmp -> next;
free(tmp);
} else {
prev = prev -> next;
}
//prev = prev -> next;
}
if (prev ->next != NULL && prev -> val == prev -> next -> val) {
prev -> next = NULL;
}
return head;
}
This post is licensed under CC BY 4.0 by the author.

