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:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
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.
var deleteDuplicates = function(head) {
for(let i = 0; i < head.length; i++){
if(head[i] === head[i + 1]){
console.log(head)
head.splice(i + 1, 1)
console.log('------', head)
i--
}
}
return head;
};
❗️ 문제를 읽고 예시를 보고 바로 코드를 작성했는데 분명히 맞아야할 코드인데 테스트케이스가 통과되지 않아서 콘솔까지 찍었는데 정답이 제대로 나와서 의아했다.
알고보니 자료구조 알고리즘을 통해 풀어야 하는 문제였다.
코드를 작성하는 칸 위에 힌트가 있었는데 그걸 놓쳤다😹
힌트⬇️
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
let current = head;
while (current !== null && current.next !== null) {
if (current.val === current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
};
✅ 오랜만에 자료구조 알고리즘을 통해 푸는거라 기억을 되살리는데 시간이 조금 걸리긴 했지만 덕분에 복습 완료:)