Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 92. Reverse Linked List II in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jul 21, 2022·

1 min read

URL

leetcode.com/problems/reverse-linked-list-ii

Code

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

type List =
    | Leaf
    | Node of int * List

let reverseBetween (head: List) (left: int) (right: int) : List =
    let rec collectNums node i left right acc =
        if i > right then
            acc
        else
            match node with
            | Leaf -> failwith "never reach here"
            | Node (v, next) ->
                if i >= left then
                    collectNums next (i + 1) left right (v :: acc)
                else
                    collectNums next (i + 1) left right acc

    let rec reverseBetween' node i left right nums =
        match nums with
        | [] -> node
        | h :: t ->
            match node with
            | Leaf -> Leaf
            | Node (v, next) ->
                if i >= left then
                    Node(h, reverseBetween' next (i + 1) left right t)
                else
                    Node(v, reverseBetween' next (i + 1) left right nums)

    let nums = collectNums head 1 left right []
    reverseBetween' head 1 left right nums
 
Share this