Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 876. Middle of the Linked List in F#

Shohei Yoshida's photo
Shohei Yoshida
·Dec 5, 2022·

1 min read

URL

leetcode.com/problems/middle-of-the-linked-..

Code

github.com/syohex/dotnet-study/blob/master/..

type List =
    | Leaf
    | Node of int * List

let middleNode (head: List) : List =
    let rec middleNode' node n =
        match node with
        | Leaf -> None, n
        | Node(_, next) ->
            let node', len = middleNode' next (n + 1)

            match node' with
            | Some(_) -> node', len
            | None -> if n = len / 2 then Some(node), len else None, len

    middleNode' head 0 |> fst |> Option.get
 
Share this