X DAYS

:

HOUR

:

MINS

:

SEC

Copied to Clipboard
Reverse a Linked List in groups of given size.
Medium Accuracy: 45.83% Submissions: 100k+ Points: 4

Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed (See Example 2 for clarification).

Example 1:

Input:
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed first
and then the next 4 elements 5,6,7,8. Hence, the


Example 2:

Input:
K = 3
Output: 3 2 1 5 4
Explanation:
The first 3 elements are 1,2,3 are reversed
first and then elements 4,5 are reversed.Hence,
the resultant linked list is 3->2->1->5->4.


You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size and return the head of the modified linked list.

Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)

Constraints:
1 <= N <= 104
1 <= k <= N

We are replacing the old Disqus forum with the new Discussions section given below.

### Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

#### My Submissions:  