Middle of the Linked List
You get the head of a linked list. Return its middle node. When the length is even there are two middle nodes, and the answer is the second of them. Our example: 5 → 2 → 7 → 4 → 9 → 1 → 6 → 3, eight nodes — the middle nodes are 4 and 9, so the answer is the node 9.
- input
head: the head of a linked list ofnnodes.- returns
- The middle node of the list; when
nis even there are two middle nodes, and the answer is the second. It is printed as the list from it to the end. - constraints
- 1 ≤ n ≤ 100
- 1 ≤ Node.val ≤ 100
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* 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}
*/
function middleNode(head) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more fast and slow pointers problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.