Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
reverseKGroupFromEnd
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
var l = (head => {
var l = 0;
while(head)
head = head.next, l++;
return l;
})(head);
var tail = {next:head};
var result = tail;
for(var j = 0; j < l % k; j ++)
tail = tail.next;
var groupHead = tail.next;
for(var j = 0; j < (l - l % k)/k ; j++) {
var last = null;
var current = groupHead;
var next = current.next;
for(var i = 0; i < k; i++) {
current.next = last;
last = current;
current = next;
if(current)
next = current.next;
}
tail.next = last;
tail = groupHead;
groupHead = current;
}
tail.next = groupHead;
return result.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment