카테고리 없음

leetcode0019 - Remove Nth Node From End of List / Medium / TypeScript

eumjo_o 2023. 4. 30. 23:25

 

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

 

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

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    const nodeList = [];
    let currNode = head;

    while(currNode) {
       nodeList.push(currNode);
       currNode = currNode.next;
    }

    if(nodeList.length-n-1 < 0) {
        return head.next;
    } else {
        nodeList[nodeList.length-n-1].next = nodeList[nodeList.length-n-1].next?.next;
    }

    return head;
};

 

Time Complexity: O(N), Space Complexity: O(N)

  • head ListNode의 길이만큼 순회하기 때문에 time complexity는 O(N)
  • head ListNode의 길이만큼 데이터를 저장하고 있기 때문에 space complexity O(N)

head ListNode를 array에 하나씩 담아주고, 끝에서 n-1 번째의 다음 Node를 n+1번째 노드로 연결해준다.
이 때 n-1 번째 array item이 없는 경우는 n번째 요소가 head의 첫번째 요소라는 의미이기 때문에, 바로 head.next를 return 해준다.