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 One:
Input: head = [1,1,2]
Output: [1,2]
Example Two:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Solution:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummyNode = new ListNode();
dummyNode.next = head;
while(head != null && head.next != null){
if(head.val == head.next.val){
head.next = head.next.next;
}else{
head = head.next;
}
}
return dummyNode.next;
}
}
Hints:
Logics:
- Set one dummyNode
- have the base case: while head is not null and head.next is not null
- compare the value between head and head.next
- if they are the same, head.next is head.next.next
- else head is set for head.next
Tips:
- the head of listNode is different every time
- set one dummyNode is necessary
- return dummyNode.next