Flip linked lists in groups of K

You’re given a list and you flip it over in groups of k nodes, and you return the flipped list

Code implementation

var reverseKGroup = function(head, k) {
  if(! head)return null;
  let ret = new ListNode(-1,head); // Create a dummy head
  let pre = ret; // The p node points to the virtual head, so that p is equal to the previous node of the region to be flipped
  do {
    pre.next = reverse(pre.next, k); // p.next represents the last node of the flipped list
    for (let i = 0; i < k && pre; i++) {
      pre = pre.next; // Take k steps back
    }
    if(! pre)break; // If pre is empty, you have reached the end of the list and stop the loop
  } while (1);
  return ret.next; // Return the flipped list
};
var reverse = function(head,n){ // roll the list from the incoming header to the NTH node
  let pre = head;
  let cur = head;
  let con = n;
  while (--n && pre) pre = pre.next; // Check whether n nodes are sufficient
  if(! pre)return head; // If pre does not exist, there are not enough nodes
  pre = null; / / empty
  while (con--) [cur.next, pre, cur] = [pre, cur, cur.next] ; // Flip the linked list
  head.next = cur;
  return pre; // Return the flipped list
}
Copy the code