Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Solution : Reverse a LinkedList keeping counter, to keep node count along with it.
Algo :
Example: Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3 Output: 3->2->1->6->5->4->8->7->NULL.
Solution : Reverse a LinkedList keeping counter, to keep node count along with it.
Algo :
- Cur = Head, Next = Null, Pre = Null
- While (Curr != NULL AND Counter < k ) //till the end & counter to keep less than input k
- next = cur -> nextt
- cur-> nextt = pre
- pre = cur
- cur = next
- count ++;
- if ( next != NULL)
- head->next = reverse(next, k);
- return prev;
Step 3 : is to reverse next k node,
so till the end of linked list we are reversing each k nodes.
Step 4 : prev will be head of this linkedlist, return it.