c - Delete N nodes after M nodes in Linked list -
i wrote c program deleting n nodes after m nodes. can't figure out why not working. using head node rather head pointer. use head node rather head pointer ?
here 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); }
fixes following:
for(i=1;i<m && cur != null;i++) //replace ',' && { 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); }
Comments
Post a Comment