89. The chain of intermediate node
Topic Link
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/middle-of-the-linked-list
Title Description
Given a non-empty list with a single head of the first node, an intermediate node list returned.
If there are two intermediate nodes, the second intermediate node is returned.
Example 1:
Input: [1,2,3,4,5]
Output: node 3 (SEQ form: [3,4,5]) in the list of
returned node is 3. (This evaluation system is expression of the sequence node [3,4,5]).
Note that, we return an object of type ListNode ANS, so that:
ans.val. 3 =, = ans.next.val. 4, ans.next.next.val =. 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: this list node 4 (SEQ form: [4,5,6])
Since the list has two intermediate nodes, values of 3 and 4, we return to the second node.
Key Technology
The values in the list into an array.
Topic analysis
- Because the list can not be accessed by the index element, so traverse the list, the list of the elements into an array;
- Intermediate value of the output array.
- Note: If there are two intermediate values, return to the second intermediate value.
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var middleNode = function(head) { if(!head) return; let res = []; while(head){ res.push(head); head = head.next; } return res[Math.floor(res.length/2)]; };