마지막 LinkedList에서 N번째 노드 삭제

5545 단어 leetcodejavascript
접근법 1:

var removeNthFromEnd = function(head, n) {
    let length = 0;
    let current = head;

    while(current){
        current = current.next;
        length++;
    };

    let reachTill = length - n;

    current = head;
    let previous=head;
    length = 0;

    if(reachTill === 0) return head.next;

   while (current) {
       if(length === reachTill){
           break;
       }
       length++
    previous = current;
    current = current.next;
   }

    previous.next = current.next;
    return head;
};


접근 2:

var removeNthFromEnd = function(head, n) {
   let fast= head;
   let slow = head;


    for(let i=0; i< n; i++){
        fast=fast.next;
    }

    console.log(fast)

  if (!fast) return head.next;

  while (fast.next) {
    fast = fast.next;
    slow = slow.next;
  }

  slow.next = slow.next.next;
  return head;
};

좋은 웹페이지 즐겨찾기