Skip to content

Instantly share code, notes, and snippets.

@andersonleite
Forked from mauricioaniche/Albie.java
Last active July 14, 2019 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonleite/4d12c234fc09831a409df09bac90d1ae to your computer and use it in GitHub Desktop.
Save andersonleite/4d12c234fc09831a409df09bac90d1ae to your computer and use it in GitHub Desktop.
Reverse Nodes In K Groups
// Singly-linked lists are already defined with this interface:
// function ListNode(x) {
// this.value = x;
// this.next = null;
// }
//
function reverseNodesInKGroups(l, k) {
return calculate(l, k , Math.floor(sizeOf(l)/k))
}
const calculate = (l, k, numberOfInteractions) => {
if(numberOfInteractions===0) { return l }
let first = l
let previous = l
let current = l
let lostLink = current.next
for(let i = 0; i < k-1; i++){
current = lostLink
lostLink = current.next
current.next = previous
previous = current
}
first.next = calculate(lostLink, k, numberOfInteractions-1)
return current
}
const sizeOf = (l) => {
let size = 0
while(l){ size++; l = l.next }
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment