Linked list Deletion in c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node node;
//functionto create a linked list
node * createLinkedlist(int n);
void display(node *start);
node* deletenode(node *head,int pos);
int main()
{
int n=0,k=0;
node *head=NULL;
node * HEAD =NULL; //address of first node
printf("ENter Number of nodes : ");
scanf("%d",&n);
HEAD = createLinkedlist(n);
display(HEAD);
printf("Enter position to delete a node");
scanf("%d",&k);
HEAD=deletenode(HEAD,k);
display(HEAD);
return 0;
}
node* deletenode(node* head, int pos) {
node *i,*j;
int count=0;
if(pos==0 &&head->next!=NULL){
j=head;
head=head->next;
free(j);
}
else{
i=head;
while(i->next!=NULL&&count<pos){
j=i;
i=i->next;
count++;
}
j->next=i->next;
free(i);
}
return(head);
}
node *createLinkedlist(int n)
{
int i=0;
node *head=NULL;
node *temp=NULL;
node *p = NULL;
for(i=0;i<n;i++)
{
//create indibidual isolated nodes
temp=(node*)malloc(sizeof(node));
printf("enter data for %d",(i+1));
scanf("%d",&temp->data);
temp->next=NULL;
if(head==NULL)
{
head= temp; //make temp as first node. created individually
}
else
{
p=head;
while(p->next !=NULL)
{
p=p->next;
}
p->next=temp;
}
}
return head;
}
void display(node *start)
{
node *p = start;
while(p != NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
Comments
Post a Comment