Search for a command to run...
Identify groups of size K, reverse each group, and stitch them back together in place
Initialization
temp initialized at head (5). prevLast starts as null.
Group-by-Group Reversal
1class Solution {2 reverseLinkedList(head) {3 let temp = head;4 let prev = null;5 while (temp !== null) {6 let front = temp.next;7 temp.next = prev;8 prev = temp;9 temp = front;10 }11 return prev;12 }13 14 getKthNode(temp, k) {15 k -= 1;16 while (temp !== null && k > 0) {17 k--;18 temp = temp.next;19 }20 return temp;21 }22 23 reverseKGroup(head, k) {24 let temp = head;25 let prevLast = null;26 27 while (temp !== null) {28 let kThNode = this.getKthNode(temp, k);29 30 if (kThNode === null) {31 if (prevLast !== null) {32 prevLast.next = temp;33 }34 break;35 }36 37 let nextNode = kThNode.next;38 kThNode.next = null;39 40 this.reverseLinkedList(temp);41 42 if (temp === head) {43 head = kThNode;44 } else {45 prevLast.next = kThNode;46 }47 48 prevLast = temp;49 temp = nextNode;50 }51 return head;52 }53}