C Program to Implement Doubly Linked List (Create and Display)
A Doubly Linked List is a linear data structure where each node contains data, a pointer to the next node, and a pointer to the previous node. In this program, we will implement Create and Display operations in a simple student-friendly way.
š Problem Statement
Q1. A) Write a C program to implement a doubly linked list with Create and Display operation.
š” Logic (Simple Steps)
š¹ Create Operation
- Define a structure with:
dataprevpointernextpointer
- For each new node:
- Allocate memory using
malloc(). - If list is empty ā make it head.
- Otherwise:
- Move to last node.
- Link last nodeās
nextto new node. - Set new nodeās
prevto last node.
- Allocate memory using
š¹ Display Operation
- Start from head.
- Traverse using
nextpointer. - Print each nodeās data.
š» Source Code (Simple Version)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
int main()
{
struct node *head = NULL, *newnode, *temp;
int n, i, value;
printf("Enter number of nodes: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter value: ");
scanf("%d", &value);
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = value;
newnode->prev = NULL;
newnode->next = NULL;
if(head == NULL)
{
head = newnode;
}
else
{
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newnode;
newnode->prev = temp;
}
}
printf("Doubly Linked List elements are:\n");
temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
š„ļø Sample Output
Enter number of nodes: 3
Enter value: 10
Enter value: 20
Enter value: 30
Doubly Linked List elements are:
10 20 30
š Viva Questions with Answers
1. What is a doubly linked list?
A doubly linked list is a list where each node contains two pointers: one to the next node and one to the previous node.
2. What are the advantages of a doubly linked list?
It allows traversal in both forward and backward directions.
3. What does the prev pointer store?
It stores the address of the previous node.
4. What is the first nodeās prev value?
It is NULL.
5. What function is used for dynamic memory allocation?
malloc() is used.
