Write a ‘C’ program to create doubly link list and display nodes having odd value.
#include <stdio.h>
#include <stdlib.h>
// Structure of a doubly linked list node
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Function to create a doubly linked list
struct Node* createList(int n) {
struct Node *head = NULL, *temp = NULL, *newNode = NULL;
int value;
for (int 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;
temp = newNode;
} else {
temp->next = newNode;
newNode->prev = temp;
temp = newNode;
}
}
return head;
}
// Function to display nodes with odd values
void displayOddNodes(struct Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
printf("Nodes with odd values:\n");
while (temp != NULL) {
if (temp->data % 2 != 0) {
printf("%d ", temp->data);
}
temp = temp->next;
}
printf("\n");
}
// Main function
int main() {
struct Node* head = NULL;
int n;
printf("Enter number of nodes: ");
scanf("%d", &n);
head = createList(n);
displayOddNodes(head);
return 0;
}
