-
-
Save andersonleite/4d12c234fc09831a409df09bac90d1ae to your computer and use it in GitHub Desktop.
Reverse Nodes In K Groups
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
// 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