LeetCode Remove Duplicates from Sorted List (JavaScript)

2025. 12. 9. 17:22·코딩테스트/LeetCode

링크 : 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
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Unique Paths (JavaScript)
  • LeetCode Pascal's Triangle (JavaScript)
  • LeetCode Climbing Stairs (JavaScript)
  • LeetCode Sqrt(x) (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (215) N
      • 프론트엔드 (65) N
        • JavaScript (52) N
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (128) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (39) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Remove Duplicates from Sorted List (JavaScript)
상단으로

티스토리툴바