Reverse Nodes in k-Group
ID: 450; hard; K组翻转链表
Last updated
ID: 450; hard; K组翻转链表
Last updated
We use a similar approach used in Reverse Linked List II. Using the helper function reverseBetween
, we reverse k
nodes each time and return the end of of the linked list for each k
group. If the end node is null, we know that the remaining nodes cannot constitute a k
group.
Inside the helper function, note that the head
is always one node before the starting node that is to be reversed. Then, we keep track of the first node that is to be reversed (firstNode
) and the node after k-th node (kNextNode
) because we need to connect the reversed linked list eventually with a start and an end.