C Program to Create a Doubly Linked List and Display Nodes with Odd Values
A Doubly Linked List is a 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 create a doubly linked list and display only the nodes containing odd values.
📝 Problem Statement
Q1. A) Write a ‘C’ program to create a doubly linked list and display nodes having odd value.
💡 Logic (Simple Student-Friendly Steps)
🔹 Create Operation
- Define a structure for a node with:
dataprevpointernextpointer
- For each new node:
- Allocate memory using
malloc(). - Assign the value to the node.
- If list is empty, make it head.
- Otherwise, attach the node at the end.
- Allocate memory using
🔹 Display Odd Nodes
- Start from head.
- Traverse using the
nextpointer. - Check if
data % 2 != 0. - If yes, print the value.
💻 Source Code (Student-Friendly)
#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 for node %d: ", i+1);
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("Nodes with odd values are:\n");
temp = head;
while(temp != NULL)
{
if(temp->data % 2 != 0)
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
🖥️ Sample Output
Enter number of nodes: 5
Enter value for node 1: 10
Enter value for node 2: 15
Enter value for node 3: 20
Enter value for node 4: 25
Enter value for node 5: 30
Nodes with odd values are:
15 25
🎓 Viva Questions with Answers
1. What is a doubly linked list?
A linked list where each node has a next and a previous pointer.
2. How do you identify odd values?
By checking if data % 2 != 0.
3. What is the first node called?
The head node.
4. How is a new node added at the end?
By traversing to the last node and updating its next pointer to the new node.
5. What is the advantage of a doubly linked list over a singly linked list?
It allows traversal forward and backward.
