Skip to content
Onsite

Reverse Nodes in k-Group

HardP2Coding

Given the head of a singly linked list and an integer k, reverse the nodes of the list k at a time and return the head. Only full groups of k nodes are reversed; if fewer than k nodes remain at the end, leave them as they are. Change the pointers; do not just swap values. A list node has val and next. The ListNode class is already defined for you.

Example 1

Input
head = [1,2,3,4,5], k = 2
Output
[2,1,4,3,5]

Example 2

Input
head = [1,2,3,4,5], k = 3
Output
[3,2,1,4,5]

Example 3

Input
head = [1,2,3], k = 1
Output
[1,2,3]

Constraints

  • 1 <= k <= number of nodes <= 5000
  • 0 <= Node.val <= 1000

Hints

Run checks the 3 visible tests, Submit all 11.