DATA STRUCTURES PROGRAM • DOUBLY & CIRCULAR LINKED LISTS
Insert at the End of a Doubly Linked List
Learn how to insert at the end 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, 10); dappend(&head, 20); dappend(&head, 30);
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 the former tail and new node through both next and previous pointers.
- Display the computed result.
Connect the former tail and new node through both next and previous pointers.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
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.
