Search code examples
cpointerslinked-listtraversal

Delete N nodes after M nodes in Linked list


I wrote a C program for deleting n nodes after m nodes. I can't figure out why its not working. Am using a head node rather than a head pointer. Is it good to use head node rather than head pointer ?

Here is my code :

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};

struct node* create()
{
    struct node *head=malloc(sizeof(struct node));
    head->next=NULL;
    return head;
}

void insert(struct node *head,int x)
{
    struct node *temp=head;
    struct node *new=malloc(sizeof(struct node));
    new->data=x;
    new->next=NULL;
    while(temp->next!=NULL)
        temp=temp->next;
    temp->next=new;

}

void display(struct node *head) {
    struct node *temp=head->next;
    while(temp!=NULL)
    {
        printf("\n%d\n",temp->data);
        temp=temp->next;
    }
}

void skipMDeleteN(struct node *head,int m,int n)
{
    int i;
    struct node *cur=head->next;
    while(cur)
    {printf("djhfj");
        for(i=1;i<m,cur!=NULL;i++)
            cur=cur->next;

        if(cur==NULL) return;

        struct node *t=cur->next;
        for(i=1;i<=n;i++)
        {
            struct node *temp=t;
            t=t->next;
            free(temp);
        }
        cur->next=t;
        cur=t;
    }
}

int main()
{
    struct node *head=create();
    int i;
    for(i=1;i<=10;i++)
    {
        insert(head,i);
    }
    int m=2,n=2;
    skipMDeleteN(head,m,n);
    display(head);
}

Solution

  • Fixes as following:

    for(i=1;i<m && cur != NULL;i++) //Replace ',' with &&
    {
        cur=cur->next;
    }
    if(cur==NULL) return;
    
    struct node *t=cur->next;
    for(i=1;i<=n && t!=NULL;i++) // Check if t reaches end of node.
    {
        struct node *temp=t;
        t=t->next;
        free(temp);
    }