[LeetCode] 203. Remove Linked List Elements

Chobby·2025년 2월 7일
1

LeetCode

목록 보기
220/427

😎풀이

  1. 더미 노드 생성
  2. head와 연결
  3. 순회 노드 생성
  4. 모든 노드 순회O(n)
    4-1. val에 해당하는 값을 가진 노드 생략
  5. 새로운 head 반환
function removeElements(head: ListNode | null, val: number): ListNode | null {
    // 임의 노드 시작점 선언
    const dummy = new ListNode()
    // head 연결
    dummy.next = head
    // 순회 노드 선언
    let current = dummy
    while(current && current.next) {
        // 특정 값의 노드는 건너뜀
        if(current.next.val === val) current.next = current.next.next
        else current = current.next
    }

    return dummy.next
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글