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

[투포인터][JavaScript][LeetCode] #876. Middle of the Linked List 본문

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

[투포인터][JavaScript][LeetCode] #876. Middle of the Linked List

큐 2023. 4. 3. 10:00
728x90
반응형

#투포인터  #EASY

 

Middle of the Linked List - LeetCode

Can you solve this real interview question? Middle of the Linked List - Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.   Example 1: [https://assets.leetcode.

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Middle of the Linked List
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.

🎃 제한 사항
The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100

입출력 예

example head result
[1, 2, 3, 4, 5] [3, 4, 5]
[1, 2, 3, 4, 5, 6] [4, 5, 6]

 

🌷 내 코드

1. 투포인터

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
 
var middleNode = function (head) {
  let slow = head;
  let fast = head;

  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next; 
    // slow보다 두 배로 빠르게 끝에 도달하므로, fast가 끝에 도달했을 때 slow는 중간일 것
  }
  return slow;
};

 

🌷 코멘트

처음에 노드를 어떻게 다루는지 몰라가지구 ,,,, ㅎ
나중에 보니 주석에 적혀 있었는데,
문제 풀이 시작하자마자 주석 바로 지우고 시작해서 + 콘솔 찍으면 그냥 Array 나와서
왜 slice가 안먹는건지 한~참 왔다갔다했다 ㅠ 애꿎은 MDN문서만 만지작만지작

 


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

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

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

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

github.com

728x90
반응형