# Reverse Nodes In k-Group Problem Solution

Reverse Nodes In k-Group Problem: Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return the modified list.

`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example:

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

## Problem Solution In Python

``````class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
# Calculate Length
l=0

while t:
l+=1
t=t.next

# Get multiple length of k
l//=k

for _ in range(1,k):

l-=1
``````

## Problem Solution In Java

``````public ListNode reverseKGroup(ListNode head, int k) {
int movements = k;
while(tail != null && movements > 1){
tail = tail.next;
movements--;
}

ListNode next = tail.next;
tail.next = null;
}
ListNode prev = null;
while(cur != null){
ListNode nextTemp = cur.next;
cur.next = prev;
prev = cur;
cur = nextTemp;
}
return prev;
}
``````

## Problem Solution In C++

``````class Solution {
public:

while(temp->next!=NULL)temp=temp->next;
}
ListNode* reverseKGroup(ListNode* head, int k) {
int cnt=k-1;
while(cnt && tmp->next!=NULL){
tmp=tmp->next;cnt--;
}
if(cnt!=0)
ListNode* t=reverseKGroup(tmp->next,k);
tmp->next=NULL;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next=t;

}
};
``````

## Problem Solution In C

``````struct ListNode* kSteps(struct ListNode* head, int k) {
for (int i = 1; i < k && head; i++)

return NULL;
}

struct ListNode* reverseKGroup(struct ListNode* head, int k) {
if (k < 2) return head;
struct ListNode* prev = kSteps(head, k);
if (prev) {
struct ListNode* next = head, * curr = head, * tail = curr;
prev = prev->next;
for (int i = 0; i < k; i++) {
next = next->next;
curr->next = prev;
prev = curr;
curr = next;
}
while (prev = kSteps(curr, k)) {
tail->next = prev;
tail = curr;
prev = prev->next;
for (int i = 0; i < k; i++) {
next = next->next;
curr->next = prev;
prev = curr;
curr = next;
}
}
}