Quick actions

cmd+k|ctrl+k

Navigation

Languages

kth-last-node.js

Snippet info

Language

JavaScript

Visibility

public

Author

masonwan

Created

2017-03-15T17:04:48Z

Updated

2017-11-01T21:17:14Z

const assert = require('assert')

class Node {
    constructor(value) {
        this.value = value
    }
}

class NodeBuilder {
    add(value) {
        if (this.first == null) {
            this.first = this.last = new Node(value)
        } else {
            this.last.next = new Node(value)
            this.last = this.last.next
        }
        return this
    }

    build() {
        return this.first
    }
}

Node.add = (value) => {
    let builder = new NodeBuilder()
    return builder.add(value)
}

const node = Node
    .add('this')
    .add('is')
    .add('mason')
    .build()

let lastNode = kthLastNode(node, 1);
assert(lastNode === 'mason', lastNode)

function kthLastNode(node, kth) {
    let count = 0
    let first = null
    while (node != null) {
        count += 1
        if (first == null) {
            first = node
        } else {
            if (count > kth) {
                first = first.next
            }
        }
        node = node.next
    }
    return first.value
}
INFO