Middle of the Linked List
You get the head of a singly linked list. Return the middle node. If the number of nodes is even, there are two middle positions; return the second of those (the one closer to the tail).
Return the node itself. The examples display the suffix beginning at that node.
Input Format
Implement middleNode(head). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 ยท Run Sample
Input
head = [1,2,3,4,5] Output
[3,4,5] Example 2
Input
head = [1,2,3,4,5,6] Output
[4,5,6] Constraints
- 1 to 100 nodes
- 1 <= Node.val <= 100
Test Cases (2)
Case 1
Args: [[1,2,3,4,5]]
Expected: [3,4,5]
Case 2
Args: [[1,2,3,4,5,6]]
Expected: [4,5,6]
Topics
Slow and Fast Pointers
function middleNode(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
return slow;
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.