Reverse Nodes in k-Group
ID: 450; hard; K组翻转链表
Solution 1 (Java)
Notes
We use a similar approach used in Reverse Linked List II. Using the helper function
reverseBetween
, we reversek
nodes each time and return the end of of the linked list for eachk
group. If the end node is null, we know that the remaining nodes cannot constitute ak
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.
Last updated