# Input List => 1 2 3 4 5 6 7 8 9 10 11 Output List => 3 2 1 6 5 4 9 8 7 10 11

345 views

Can someone please write a C program to reverse "N" nodes of list. In the above question N= 3.
Program should be generic so it can work for any value assigned to N.

Input List => 1 2 3 4 5 6 7 8 9 10 11
Output List => 3 2 1 6 5 4 9 8 7 10 11
for N=3

Input List => 1 2 3 4 5 6 7 8 9 10 11
Output List => 4 3 2 1 8 7 6 5 9 10 11
for n=4

posted Oct 10, 2013

``````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;
}
return prev;
}

struct node * reverse_list_node (struct node * head, int N)
{
struct node *tmp = beg;

{
{
tmp->next = reverse_num_node (beg, &next_head, N);
tmp = beg;
}
}
}
``````

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.

``````struct Node *NplusOnethNode(struct Node *head, int n)
{
struct Node *nth_node;
int p;
for(p=0; nth_node = head &&(i<n); i++, nth_node = nth_node->next);
if((p==n)&&(nth_node!= NULL))
{
return nth_node;
}
}

int ContainsNnodes(struct Node *head, int n)
{
int i;
if(i==n)
return i;
return 0;
}

struct Node *reverseNnodes(struct Node *head, int n)
{
int i;
if(n==0 || n== 1)
if(ContainsNnodes(nptr, n-1))
else
while( nptr && ContainsNnodes(nptr, n))
{
temp =  NplusOnethNode(nptr, n);
i =0;
while(i<n)
{
next = nptr->next;
nptr->next =  temp;
temp = nptr;
nptr = next;
i++;
}
}
}
``````
answer Oct 10, 2013 by anonymous
Can you please explain the complexity of code.

As per my understanding complexity of your code is O(n2).
Similar Questions