Basic Implementation of Doubly Linked List

Various implementation using doubly linked list like insertion, deletion etc.

Node Structure

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

Insertion

Insertion at Head and Insertion at Tail

void insertAtEnd(int val)
{
    node *temp = new node;
    temp->data = val;
    temp->next = NULL;
    temp->prev = NULL;

    if (head == NULL)
    {
        head = temp;
    }
    else
    {
        node *p = head;
        while (p->next != NULL)
        {
            p = p->next;
        }
        p->next = temp;
        temp->prev = p;
    }
}

void insertAtBegin(int val)
{
    node *temp = new node;
    temp->data = val;
    temp->next = NULL;
    temp->prev = NULL;

    if (head == NULL)
    {
        head = temp;
    }
    else
    {
        node *p = head;
        temp->next = p;
        p->prev = temp;
        head = temp;
    }
}

Insertion at any random position

void insertAtPos(int pos, int val)
{
    int i = 0;
    int len = getLen();
    if (pos < 0 || pos > len - 1)
    {
        return;
    }
    node *p = head;
    node *q = NULL;
    while (i < pos && p->next != NULL)
    {
        q = p;
        p = p->next;
        i++;
    }
    node *temp = new node;
    temp->data = val;
    temp->next = NULL;
    temp->prev = NULL;
    q->next = temp;
    temp->prev = q;
    temp->next = p;
    p->prev = temp;
}

Deletion

Last updated