Problem 255452 · medium · Level 02 Linear Data Structures

Reverse in Blocks of k

linked list · reversal · pointer manipulation

Given the head of a singly linked list and an integer k, reverse the nodes in consecutive blocks of k and return the head. If fewer than k nodes remain at the end, that tail is left in its original order.

Examples

Input:  head = 9 -> 8 -> 7 -> 6 -> 5, k = 2
Output: 8 -> 9 -> 6 -> 7 -> 5

Input:  head = 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80, k = 3
Output: 30 -> 20 -> 10 -> 60 -> 50 -> 40 -> 70 -> 80
Explanation: the last two nodes do not fill a block of 3, so they keep their order.

Constraints

  • Target: O(n) time, O(1) extra space

Goals

  • Check that a full block exists before reversing it
  • Chain several reversed blocks together
Starting Python…