[leetCode] 876. Middle of the Linked List
3335 ワード
🧪 Description
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:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
💊 Solution
この問題は接続リストを使用する問題です.
データ構造接続リストとは?
接続リストにアクセスする方法を知る必要があります.
/**
* 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 slow = head;
let fast = head;
while(fast !== null) {
fast = fast.next;
if (fast === null) break;
else {
fast = fast.next;
}
slow = slow.next;
}
return slow;
};
🧫 Result
Runtime
76 ms, faster than 57.09% of JavaScript online submissions for Middle of the Linked List.
Memory Usage
39.2 MB, less than 7.70% of JavaScript online submissions for Middle of the Linked List.
Reference
この問題について([leetCode] 876. Middle of the Linked List), 我々は、より多くの情報をここで見つけました https://velog.io/@gygy/leetCode-876.-Middle-of-the-Linked-Listテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol