Problem: Given a linked list and a positive number K, reverse every K nodes in the list.
For example:
For example:
Input L1: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL
K = 3
Output: 3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 8 -> 7 -> NULL
Input L2: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
K = 2
Output 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL
Method 1: Recursive Method- Reverse the first sub-list of size k.
- While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev.
- Now next points to (k+1)th node
- head->next = reverse(next, k), Recursively call for rest of the list and link the two sub-lists
- return prev, prev becomes the new head of the list
Node reverseKNodes(Node *head, int k)
{
Node curr = head;
Node next = null;
Node prev = null;
int count = 0;
/* Reverse first k nodes of linked list */
while (count < k && curr != null)
{
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
/* next is now a pointer to (k+1)th node
Recursively call for the list starting from current.
And make rest of the list as next of first node */
if (next != null)
head.next = reverseKNodes(next, k);
/* prev is now head of input list */
return prev;
}
Time Complexity: O(n)