Created
November 12, 2018 00:15
-
-
Save AlexeiDarmin/24e13068b107a42d315763336cb87749 to your computer and use it in GitHub Desktop.
return the kth to last node in a linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function returnKthToLast(head: Node, k: number): Node | null { | |
let delta = 0 | |
let node = head | |
while (delta < k) { | |
node = node.next | |
++delta | |
if (!node) { | |
return null | |
} | |
} | |
let kthNode = node | |
while (true) { | |
if (node.next) { | |
node = node.next | |
kthNode = kthNode.next | |
} else { | |
return kthNode | |
} | |
} | |
} | |
class Node { | |
public next:any | |
public data: number | |
constructor(num: number) { | |
this.data = num | |
} | |
public appendToTail = (num: number) => { | |
const newNode = new Node(num) | |
let node = this | |
while (node.next != null) { | |
node = node.next | |
} | |
node.next = newNode | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment