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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
10 20 30
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
10 20 30
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Connect both directions between the new node and old head before replacing head.
- 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.
