Abhishek Jha / April 03, 2022
Reverse Nodes in k-Group is one of the most frequently asked interview problems related to Linked list, in this blog I'm going to explain it's intuitive recursive solution
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]class Solution {public:ListNode* reverseKGroup(ListNode* head, int k) {// if head is null or k = 1, do nothingif(!head or k == 1) return head;ListNode *oldHead = head, *newHead = NULL, *curr = head;// go to kth node of group, that will be newHead after reversalfor(int i = 0; i < k-1; i++) {curr = curr->next;// if less than k nodes are left, do nothingif(!curr) return head;}newHead = curr;// reversing group of k nodesListNode *prev = NULL, *nxt = NULL;curr = head;for(int i = 0; i < k; i++) {nxt = curr->next;curr->next = prev;prev = curr;curr = nxt;}// attach result of recursively solving remaining n-k nodes// to oldHead and return newHeadoldHead->next = reverseKGroup(curr, k);return newHead;}};
If you want article on any specific DSA, CP or Dev related topics. Then do let me know