DATA STRUCTURES PROGRAM • DOUBLY & CIRCULAR LINKED LISTS

Insert at the Beginning of a Doubly Linked List

Learn how to insert at the beginning of a doubly linked list using a clear C program.

IntermediateDoubly linked listpreviousnext

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
10 20 30

COMPLETE C PROGRAM

Complete C implementation

dsa-insert-doubly-list-beginning.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct DNode { int data; struct DNode *previous; struct DNode *next; };

struct DNode *new_dnode(int value)
{
    struct DNode *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->data = value; node->previous = NULL; node->next = NULL;
    return node;
}

void dappend(struct DNode **head, int value)
{
    struct DNode *node = new_dnode(value);
    if (*head == NULL) { *head = node; return; }
    struct DNode *tail = *head;
    while (tail->next != NULL) tail = tail->next;
    tail->next = node; node->previous = tail;
}

void dprint(const struct DNode *head)
{
    while (head != NULL) { printf("%d ", head->data); head = head->next; }
    putchar('\n');
}

void dfree(struct DNode *head)
{
    while (head != NULL) { struct DNode *next = head->next; free(head); head = next; }
}

int main(void)
{
    struct DNode *head = NULL;
    dappend(&head, 20); dappend(&head, 30);
    struct DNode *node = new_dnode(10);
    node->next = head;
    head->previous = node;
    head = node;
    dprint(head);
    dfree(head);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

10 20 30
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Connect both directions between the new node and old head before replacing head.
  3. Display the computed result.

Connect both directions between the new node and old head before replacing head.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.