Skip to content

Instantly share code, notes, and snippets.

@AlexeiDarmin
Created November 12, 2018 00:15
Show Gist options
  • Save AlexeiDarmin/24e13068b107a42d315763336cb87749 to your computer and use it in GitHub Desktop.
Save AlexeiDarmin/24e13068b107a42d315763336cb87749 to your computer and use it in GitHub Desktop.
return the kth to last node in a linked list
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