/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
if (head == null) {
return head;
}
var pointer = head;
var stack = [];
while (pointer != null && stack.length < k ) {
var temp = pointer;
pointer = pointer.next;
temp.next = null;
stack.push(temp);
}
if (stack.length < k) {
var stack2 = [];
while (stack.length > 0) {
stack2.push(stack.pop());
}
stack = stack2;
}
var nextElements = reverseKGroup(pointer, k);
var newHead = stack.pop();
var pointer2 = newHead;
while (stack.length > 0) {
pointer2.next = stack.pop();
pointer2 = pointer2.next;
}
pointer2.next = nextElements;
return newHead;
};
No comments:
Post a Comment