Skip to content

Commit

Permalink
kthToLast without using length
Browse files Browse the repository at this point in the history
  • Loading branch information
grxy committed Nov 30, 2016
1 parent f444bf7 commit 94b9fba
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/LinkedList/LinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,23 @@ class LinkedList {
isEmpty = () => this.length === 0

kthToLast = (k) => {
if (k < 0 || k > this.length - 1) {
return null;
}
let n1 = this.getHead();
let n2 = this.getHead();

let current = this.getHead();
for (let i = 0; i <= k; i++) {
if (!n1) {
return null;
}

for (let i = 0; i < this.length - 1 - k; i++) {
current = current.next;
n1 = n1.next;
}

while (n1) {
n1 = n1.next;
n2 = n2.next;
}

return current;
return n2;
}

remove = (element) => {
Expand Down

0 comments on commit 94b9fba

Please sign in to comment.