Problem 255452 · medium · Phase 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 = 1 -> 2 -> 3 -> 4 -> 5, k = 2
Output: 2 -> 1 -> 4 -> 3 -> 5

Input:  head = 1 -> 2 -> 3 -> 4 -> 5, k = 3
Output: 3 -> 2 -> 1 -> 4 -> 5

Constraints

  • 0 <= number of nodes <= 10**4
  • 1 <= k <= 10**4
  • 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…