Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time. Return the modified list. k is a positive integer and less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, leftover nodes at the end should remain as they are. Do not alter the values in the list's nodes, only rearrange the nodes themselves.

Constraints

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000
Saving… · 8 lines
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def reverseKGroup(self, head, k):
Console

Click Run to execute sample tests.