Remove every k'th node

PROBLEM :

Given a singly linked list, Your task is to remove every Kth node. The task is to complete a method deleteK that takes two argument, head of linked list and an integer k.The method returns the head of the new linked list. There are multiple test cases. For each test case, this method will be called individually.

Input:
The first line of input contains number of test cases T. Then T test cases follow. Every test case contains 3 lines.  First line of every test case contains an integer N denoting the size of the linked list . The second line contains N space separated values of the linked list. The third line contains an integer K.

Output:
Output for each test case will be space separated values of the nodes of the new transformed linked list .

Constraints:
1<=T<=50
1<=N<=100
1<=element of linked list <=1000
0<=k<=100

Example:

Input:
2
8
1 2 3 4 5 6 7 8
3
4
1 2 3 4
2

Output:
1 2 4 5 7 8
1 3

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

/* Link list Node
struct Node
{
    int data;
    struct Node* next;
};*/

/*You are required to complete this method*/


Node * deleteK(Node *head,int K)
{
    if(head==NULL||K==0)
        return head ;
       
    struct Node *ptr ;  
    if(K==1)
    {
        while(head!=NULL)
        {
            ptr=head ;
            head=head->next ;
            free(ptr) ;
        }
        return head ;
    }
   
    struct Node *temp=head ;
    int i ;
    while(temp!=NULL&&temp->next!=NULL)
    {
        i=K-1 ;
       
        while(i!=1&&temp->next!=NULL)
        {
            temp=temp->next ;
            i-- ;
        }
       
        if(temp->next==NULL)
            break ;
           
        ptr=temp->next ;
        temp->next=ptr->next ;
        free(ptr) ;
       
        temp=temp->next ;
    }
    return head ;
}

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

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 )