I took this question and Java solution from http://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/
Given a linked list, write a function to reverse every alternate k nodes Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL.
In their java code: I really don't understand why step 2) is needed. node is NOT being used anywhere else except in the first argument in kAltReverse(Node node, int k) This node argument in the method is assigned to a new variable current in every recursions. And then use current, prev, next variables in each recursions.
So why node.next = current in step2) is needed?
Node kAltReverse(Node node, int k) {
Node current = node;
Node next = null, prev = null;
int count = 0;
/*1) reverse first k nodes of the linked list */
while (current != null && count < k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
/* 2) Now head points to the kth node. So change next
of head to (k+1)th node*/
if (node != null) {
node.next = current; **// why node.next should be moved to current even though node is not impacting on anywhere else in 3), 4)???**
}
/* 3) We do not want to reverse next k nodes. So move the current
pointer to skip next k nodes */
count = 0;
while (count < k - 1 && current != null) {
current = current.next;
count++;
}
/* 4) Recursively call for the list starting from current->next.
And make rest of the list as next of first node */
if (current != null) {
current.next = kAltReverse(current.next, k);
}
/* 5) prev is new head of the input list */
return prev;
}