링크 : https://leetcode.com/problems/remove-duplicates-from-sorted-list/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.
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.
문제 풀이
tmp 포인터를 하나 만들어 다음 값과 비교하면서 next 위치를 조정해주면 됨.
tmp가 있고, 다음 tmp가 존재할 경우 반복문 진행
1. 현재 tmp의 값과 다음 tmp의 값이 같을 경우 -> 현재 tmp의 next 포인터를 다음 tmp의 next 포인터로 변경
2. 값이 다르다면 tmp의 위치를 다음 tmp로 변경 (다음 값을 다시 비교해야하기 때문)
/**
* 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 tmp = head;
while (tmp !== null && tmp.next !== null) {
if (tmp.val === tmp.next.val) {
tmp.next = tmp.next.next;
} else {
tmp = tmp.next;
}
}
return head;
};
결론
node의 next위치를 잘 조정해주는 로직을 짜야함.
head를 직접 움직이면 최종 답을 출력할 때 포인터가 달라지므로 tmp라는 임시 변수를 선언하여 tmp를 이용하여 node 사이를 계산
'코딩테스트 > LeetCode' 카테고리의 다른 글
| LeetCode Unique Paths (JavaScript) (0) | 2025.12.10 |
|---|---|
| LeetCode Pascal's Triangle (JavaScript) (0) | 2025.12.09 |
| LeetCode Climbing Stairs (JavaScript) (0) | 2025.12.08 |
| LeetCode Sqrt(x) (JavaScript) (1) | 2025.12.08 |
| LeetCode Add Binary (JavaScript) (0) | 2025.11.27 |