struct node * reverse_num_node (struct node *beg, struct node **next_head, int N)
{
struct node *prev = beg; int n = 1;
struct node *current = prev->next;
struct node *next;
if (beg == NULL)
return NULL;
while (current && ( N > n))
{
next = current->next;
current->next = prev;
prev = current;
current = next;
n++;
}
if (!current && (n < N))
{
beg = reverse_num_node (prev, next_head, n);
prev->next = NULL;
return beg;
}
*next_head = current;
return prev;
}
struct node * reverse_list_node (struct node * head, int N)
{
struct node *beg = head;
struct node *next_head = NULL;
struct node *tmp = beg;
if(head = reverse_num_node (beg, &next_head, N))
{
beg = next_head;
while(next_head)
{
tmp->next = reverse_num_node (beg, &next_head, N);
tmp = beg;
beg = next_head;
}
tmp->next = next_head;
}
return head;
}
Complexity
n => Total no of node in list.
N => No of node need to reverse.
Best case O(n). When "n" is multiple of N.
Worst Case O(n + N -1) When "n" is one less than multiple of N.