876. Middle of the Linked List
Python
Get length and travel to middle
import math
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
length = 0
cur = head
while cur:
length += 1
cur = cur.next
target = head
for i in range(math.ceil(length/2) if length % 2 == 0 else math.floor(length/2)):
target = target.next
return target
One Pass Through
(This is be used in 143. Reorder List)
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
left, right = head, head
while right and right.next:
left = left.next
right = right.next.next
return left
Javascript
var middleNode = function(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !==null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
};