-
[알고리즘] #Middle of the Linked List■ Algorithm 2022. 8. 5. 18:06
문제 출처: https://leetcode.com/problems/middle-of-the-linked-list/
Middle of the Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 해석
단일 연결 리스트의 head가 주어졌을 때, 중간 노드를 리턴하는 함수를 구현하시오. 중간 노드가 2개인 경우, 두 번째 노드를 리턴하시오.
풀이
주어진 head를 노드 배열로 변경해서 중간값을 구해서 리턴해준다.
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var middleNode = function(head) { let arr = [head] while(arr[arr.length-1].next !== null) { arr.push(arr[arr.length-1].next) } return arr[Math.floor(arr.length/2)] };
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Longest Substring Without Repeating Characters (0) 2022.08.06 [알고리즘] #Remove Nth Node From End of List (0) 2022.08.05 [알고리즘] #Reverse Words in a String III (0) 2022.08.05 [알고리즘] #Reverse String (0) 2022.08.05 [알고리즘] #Two Sum II - Input Array Is Sorted (0) 2022.08.05