Skip to main content

Deletion in Double Linked list

 




#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *prev;
    struct node *link;
};

void display(struct node *ptr)
{
    while (ptr != NULL)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->link;
    }
}
struct node *del_beg(struct node *head)
{

    struct node *ptr = head;
    head = head->link;
    head->prev = NULL;
    free(ptr);

    return head;
}

struct node *del_end(struct node *head)
{
    struct node *ptr = head;
    while (ptr->link != NULL)
    {
        ptr = ptr->link;
    }
    ptr->prev->link = NULL;
    free(ptr);
    return head;
}

struct node *del_pos(struct node *head, int pos)
{

    struct node *ptr = head;
    struct node *i;
    int j = 0;
    while (j != pos - 1)
    {
        ptr = ptr->link;
        j++;
    }
    i = ptr->link;
    ptr->link = i->link;
    i->link->prev = ptr;

    free(i);

    return head;
}

int main()
{
    struct node *a;
    struct node *b;
    struct node *c;
    struct node *d;

    a = malloc(sizeof(struct node));
    b = malloc(sizeof(struct node));
    c = malloc(sizeof(struct node));
    d = malloc(sizeof(struct node));

    a->prev = NULL;
    a->data = 1;
    a->link = b;

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

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

    d->prev = c;
    d->data = 4;
    d->link = NULL;

    display(a);
    printf("\n");
    // a = del_beg(a);
    // a = del_end(a);
    a = del_pos(a, 2);

    display(a);

    return 0;
}

Comments