Skip to main content

Deletion in Linked list

 




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

};
struct node *del_beg(struct node *head){
    struct node *ptr = head;
    head = head->link;
    free(ptr);
    return head;

}
struct node *del_pos(struct node *head, int pos){
    struct node *p = head;
    struct  node *q = head->link;
    for (int i = 0; i < pos-1; i++)
    {
        p = p->link;
        q = q->link;
    }
    p->link = q->link;
    free(q);
    return head;
   
}
struct node *del_end(struct node * head){
    struct node *p = head;
    struct  node *q = head->link;
while(q->link != NULL)
    {
        p = p->link;
        q = q->link;
    }
    p->link = NULL;
    free(q);
    return head;
   
}

void display(struct node *head){
    while(head!=NULL){
        printf(" %d ",head->data);
        head = head->link;
    }
}
int main()
{
   
      struct node *head;
    struct node *b;
    struct node *c;
    struct node *d;
   
    head = malloc(sizeof(struct node));
    b = malloc(sizeof(struct node));
    c = malloc(sizeof(struct node));
    d = malloc(sizeof(struct node));
   
    head->data = 1;
    head->link = b;

    b->data = 2;
    b->link = c;

    c->data = 3;
    c->link = d;

    d->data = 4;
    d->link = NULL;
   
   display(head);
   head = del_beg(head);
head = del_pos(head,4);
head = del_end(head);
   printf("\n");

   display(head);
    return 0;
}


Comments