Here is one way to find the kth to last element of a singly linked list.
kthToLastTry in REPL1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function findKthToLast(head, k) { let p1 = head; let p2 = head; for (let i = 0; i < k; i++) { if (p1 === null) return null; p1 = p1.next; } while (p1 !== null) { p1 = p1.next; p2 = p2.next; } return p2; } function Node(data) { this.next = null; this.data = data; } Node.prototype.addToTail = function(data) { const end = new Node(data); let current = this; while (current.next !== null) { current = current.next; } current.next = end; return end; };
|
Tests can be found at REPL.it