Capital One Interview Question

Implement a linked list and return the kth to last element

Interview Answer

Anonymous

Dec 1, 2015

function LinkedList () { this.head = null; } function Node (value) { this.value = value; this.next = null; } LinkedList.prototype.addToHead = function(el) { if (el) { var newNode = new Node(el); if(this.head === null){ this.head = newNode; } else{ newNode.next = this.head; this.head = newNode; } } else { return undefined; } }; function nthToLast (sll, k) { if (k<=0) { return null; } var pointer1 = sll.head; var pointer2 = sll.head; for (var i=0; i < k-1; i++) { // move pointer n spaces away; if (pointer2 === null) return null; pointer2 = pointer2.next; } if (pointer2 === null) return null; while (pointer2.next !== null) { pointer2 = pointer2.next; pointer1 = pointer1.next; } return pointer1; }