PROBLEM DESCRIPTION
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.
SOLUTION
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
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head;
//while list has not ended
while(temp != null){
//if next node is null, nothing more to check so return head
if(temp.next == null) return head;
//if value of current node and next node is same
if(temp.next.val == temp.val){
//remove the next node but don't move forward because there are be more than 1 duplicate
temp.next = temp.next.next;
}else{
//if value is different, move to next node
temp = temp.next;
}
}
return head;
}
}