Given a linked list, we need to write a function that reverses the nodes of a linked list ‘k’ at a time and returns modified linked list.
The following are the constraints given:
- If the no. of nodes in a link list is not a multiple of k then left-out nodes in the end should remain as it is
- You have to retain the memory address of the nodes without modifying it i.e. you can’t just interchange the values in the nodes
- Only constant memory is allowed
For example the linked list given is as follows:
Linked List : 1->2->3->4->5->6->7->8->9->10->11 -> null
For k = 2
Return Value: 2->1->4->3->6->5->8->7->10->9->11 ->null
For k = 3
Return value: 3->2->1->6->5->4->9->8->7->10->11 -> null
The following are the sequence of steps to be followed. In this solution, we will be using the reverse of a linked list solution described in previous post.
- HeaderNode is the head of the linked list
- Take three pointers StartNode, EndNode and NextNode
- Let the NextNode pointer points to HeaderNode and unlink HeaderNode
- Repeat the following steps until NextNode is null
- Point StartNode and EndNode to NextNode
- Move EndNode K nodes away from StartNode
- Point NextNode to the node next to EndNode
- Unlink EndNode from the linked list
- Now reverse the list pointed by StartNode which gives reverse of K nodes
- If HeaderNode is null point the HeaderNode to reversed list else point the reversed list to the end of the HeaderNode list
- Hence the list pointed by HeaderNode contains the K- Reverse of a linked list
Consider the following linked list where headerNode is pointing to head of the linked list:
Dry run for the above example:
Initially headerNode, startNode and endNode point to null and nextNode points to head of the list.
In the loop beginning, startNode and endNode points to nextNode.
Now endNode points to the node which is K nodes away from startNode. As K=3, startNode points to 1 and endNode points to 3.
Save nextNode point to the next node of the endNode so that we can begin the next iteration from nextNode
Now unlink the endNode from the list. And pass the list pointed by startNode to the reverse function
The reversal of the list pointed by startNode is returned as 3 -> 2 -> 1
As the headerNode is null, point startNode to headerNode and repeat the loop. Now the loop is repeated for the rest of the linked list. And the list pointed by startNode gets reversed.
As the headerNode is not null, the last element of the current headerNode list gets linked to the list pointed by startNode
As the nextNode is pointing to null, the while loop ends.
Code for the above solution: