Link : 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.
// import java.util.HashSet;
//Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class LC3 {
// public ListNode deleteDuplicates(ListNode head) {
// HashSet<Integer> hashSet = new HashSet<>();
// ListNode prev = null;
// ListNode now = head;
// while(now != null){
// if(hashSet.contains(now.val)){
// prev.next = now.next;
// } else {
// hashSet.add(now.val);
// prev = now;
// }
// now = now.next;
// }
// return head;
// }
public ListNode deleteDuplicates(ListNode head) {
// sorted! 문제 조건을 잘 읽자
ListNode prev = null;
ListNode now = head;
while(now != null){
if(prev != null && now.val == prev.val){
prev.next = now.next;
} else {
prev = now;
}
now = now.next;
}
return head;
}
}
이전 노드 -> 다음 노드
로 해준다.