Delete N nodes after M nodes of a linked list

PROBLEM :

Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list.

Input:

Complete the method which takes three argument: the head of the linked list,M an N. Function should not read any input from stdin/console.
The struct Node has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.


Output:

Function should not print any output to stdin/console


Example:

Input:
M = 2, N = 2
Linked List: 1->2->3->4->5->6->7->8
Output:
Linked List: 1->2->5->6

Input:
M = 3, N = 2
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->2->3->6->7->8

Input:
M = 1, N = 1
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->3->5->7->9

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
delete n nodes after m nodes
  The input list will have at least one element
  Node is defined as
  struct node
  {
     int data;
     struct node *next;
  }

*/

void linkdelete(struct node  *head, int M, int N)
{
    if(head==NULL)
        return ;
       
    int i ;  
    struct node *m,*n ;
   
    m=head ;
    n=head ;
   
    while(1)
    {
        i=1 ;
        while(m->next!=NULL&&i!=M)
        {
            m=m->next ;
            i++ ;
        }
       
        i=0 ;
        while(m!=NULL&&m->next!=NULL&&i!=N)
        {
            n=m->next ;
            m->next=n->next ;
            free(n) ;
            i++ ;
        }
       
        if(m->next)
            m=m->next ;
        if(m==NULL||m->next==NULL)
        break ;
    }
}



---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )