개발이 취미인 주니어 기획자

[투포인터][JavaScript][LeetCode] #19. Remove Nth Node From End of List 본문

문제 풀이/알고리즘 문제 풀이

[투포인터][JavaScript][LeetCode] #19. Remove Nth Node From End of List

큐 2023. 4. 6. 11:00
728x90
반응형

#투포인터  #MEDIUM

 

Remove Nth Node From End of List - LeetCode

Can you solve this real interview question? Remove Nth Node From End of List - Given the head of a linked list, remove the nth node from the end of the list and return its head.   Example 1: [https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg]

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Remove Nth Node From End of List
Given the head of a linked list, remove the nth node from the end of the list and return its head.

🎃 제한 사항
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

입출력 예

head n result
[1, 2, 3, 4, 5] 2 [1, 2, 3, 5]
[1] 1 []
[1, 2]
1 [1]

 

🌷 내 코드

var removeNthFromEnd = function(head, n) {
    let dummy = new ListNode(null) // [0]
    dummy.next = head // dummy: [0,1,2,3,4,5]
    
    let slow = dummy // [0,1,2,3,4,5]
    let fast = head // [1,2,3,4,5]

    // fast를 n만큼 앞으로 옮김
    for (let i=0; i<n; i++) {
        fast = fast.next 
    } 
    // fast: [3,4,5] n만큼 앞으로 간 것을 알 수 있음

    // fast가 노드에서 완전히 이탈할 때 까지
    // fast와 slow를 같은 속도로 움직임
    while (fast) {
        slow = slow.next
        fast = fast.next
    } // slow: [3,4,5], fast: []

    // dummy.next: [1,2,3,4,5]
    slow.next = slow.next.next; // slow.next.next: [5]
    // dummy.next: [1,2,3,5]
    return dummy.next 
};

 

🌷 코멘트

Linked list라는 자료구조를 몰라서 되게 간단하고 짧은 문제임에도 불구하고 엄청 엄-청 헤맸다
특히 slow랑 dummy간 관계가 이해가 안돼서 진짜 하나하나 그림그려보고..linked list에 대해서 따로 포스팅 해야겠다
문제 풀 때는 윤성우의 열혈 자료구조 이 분의 블로그를 보고 대강 이해했다ㅠㅠ 아휴

블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형