• Time:O(n)
• Space:O(n)

## C++

``````class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
return nullptr;

for (int i = 0; i < k; ++i) {
if (!tail)  // less than k nodes, do nothing
tail = tail->next;
}

}

private:
ListNode* reverse(ListNode* head, ListNode* tail) {
ListNode* prev = nullptr;

while (curr != tail) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

return prev;
}
};
``````

## JAVA

``````class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
return null;

for (int i = 0; i < k; ++i) {
if (tail == null) // less than k nodes, do nothing
tail = tail.next;
}

}

private ListNode reverse(ListNode head, ListNode tail) {
ListNode prev = null;

while (curr != tail) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}

return prev;
}
}
``````

## Python

``````class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
return None

for _ in range(k):
if not tail:  # less than k nodes, do nothing
tail = tail.next

def _reverse(self, head: Optional[ListNode], tail: Optional[ListNode]) -> Optional[ListNode]:
prev = None

while curr != tail:
next = curr.next
curr.next = prev
prev = curr
curr = next

return prev
``````

• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || k == 1)

ListNode* prev = &dummy;

for (int i = 0; i < length / k; ++i) {
for (int j = 0; j < k - 1; ++j) {
ListNode* next = curr->next;
curr->next = next->next;
next->next = prev->next;
prev->next = next;
}
prev = curr;
curr = curr->next;
}

return dummy.next;
}

private:
int length = 0;
for (ListNode* curr = head; curr; curr = curr->next)
++length;
return length;
}
};
``````

## JAVA

``````class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 1)

ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;

for (int i = 0; i < length / k; ++i) {
for (int j = 0; j < k - 1; ++j) {
ListNode next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
prev = curr;
curr = curr.next;
}

return dummy.next;
}

int length = 0;
for (ListNode curr = head; curr != null; curr = curr.next)
++length;
return length;
}
}
``````

## Python

``````class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k == 1:

length = 0
length += 1
return length

prev = dummy