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.
prompt:
Given the list of nodes is between 1 and 100.
Method a: traversing all the nodes stored in the array, and then taking the middle value is returned.
Method two: Finger speed
idea and algorithm
- When the pointer through the list with a slow slow, another pointer fast speed make it a double.
- When it reaches the end of the fast, slow necessarily in the middle.
class Solution_876 {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next; //快两倍
}
return slow;
}
}