• + 0 comments

    typescript, just recursion, not creating a stack or a dict of the visited nodes

    function traverse (llist: SinglyLinkedListNode, positionFromTail: number, found: { value: number}): number {
        if(llist.next !== null){
            const pos = 1 + traverse(llist.next, positionFromTail, found)
            if (pos === positionFromTail){
                found.value = llist.data
            }
            return pos
        }
        if (positionFromTail === 0){
            found.value = llist.data
        }
        return 0
    }
    
    function getNode(llist: SinglyLinkedListNode, positionFromTail: number): number {
        const found = {  value: 0}
        traverse(llist, positionFromTail, found)
        return found.value
    }