JSFiddle - React, Tailwind, and code Playground
by Andrew Poes
JavaScript
var Node = function() {
var next;
var data;
}
var n = new Node()
n.data = 0
var head = n
for (var i = 1; i < 6; ++i) {
var node = new Node()
node.data = i;
n.next = node
n = node
}
function traverse(head) {
var n = head
var count = 0
while (n != null) {
n = n.next
++count
}
console.log('total', count)
}
function nthToLast(head, k) {
k = Math.max(k, 1)
if (head == null) {
console.log('hit end')
return 0
} else { console.log('recurse', head.data) }
var i = nthToLast(head.next, k)
i += 1
console.log('i', i, 'head', head.data)
if (i == k) {
console.log(head.data)
}
return i
}
nthToLast(head, 3)