Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 19. Remove Nth Node From End of List in F#

Shohei Yoshida's photo
Shohei Yoshida
·Sep 28, 2022·

1 min read

URL

leetcode.com/problems/remove-nth-node-from-..

Code

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

type List =
    | Leaf
    | Node of int * List

let removeNthFromEnd(head: List) (n: int) : List =
    let rec removeNthFromEnd' node pos n =
        match node with
        | Leaf -> pos, Leaf
        | Node(v, next) ->
            let lastPos, next' = removeNthFromEnd' next (pos + 1) n
            if lastPos - pos = n then
                lastPos, next'
            else
                lastPos, Node(v, next')

    removeNthFromEnd' head 0 n |> snd
 
Share this