코딩쌀롱

[LeetCode_JS] 83. Remove Duplicates from Sorted List 본문

개발공부

[LeetCode_JS] 83. Remove Duplicates from Sorted List

이브✱ 2021. 1. 13. 16:23

문제

LeetCode 83. Remove Duplicates from Sorted List 문제

input: 싱글 링크드 리스트의 head node

output: 중복 val인 노드들을 제거한 링크드 리스트의 head node 

// Definition for singly-linked list.
function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

노드들은 val, next 속성을 가지고 있다.

나의 풀이

while문 마지막에 현재 노드를 다음 노드로 바꿔주고, 현재 노드가 끝까지 가서 null일 때 while문을 더 이상 돌지 않게 했다. 

✱바깥 while문 : 현재 노드(curr)들을 계속 이동시키면서 리스트 탐색

✱안쪽 while문 : 현재 노드의 val, 다음 노드의 val이 중복일 때 링크를 그 다음 노드로 연결해주는 것을 반복

 

if문, 안쪽 while문의 조건에 curr.next를 넣은 이유는 curr.next가 null일 때, 즉 현재 노드가 마지막 노드일 때 curr.next.val로 값 비교를 하면 런타임 에러가 나기 때문.

 

 

Comments