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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter