code to reverse a linked list in the group of k

PHOTO EMBED

Fri Jul 19 2024 06:09:29 GMT+0000 (Coordinated Universal Time)

Saved by @vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist #recursion

node* kReverse (node* head, int k) {
  // base case
  if (head == NULL) {
    return NULL;
  }

  // step 1: reverse first k nodes
  node* forward = NULL;
  node* curr = head;
  node* prev = NULL;
  int cnt = 0;
  while (curr != NULL && cnt < k) {
    forward = curr -> next;
    curr -> next = prev;
    prev = curr;
    curr = forward;
    cnt++;
    
  }
  // step 2: recursion
  if (forward != NULL) {
    head -> next = kReverse(forward, k);
    
  }
  // step 3: return head of the modified list
  return prev;
}
content_copyCOPY

https://youtu.be/fi2vh0nQLi0?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA