Implement a doubly linked list and perform various operations to understand its properties and applications in C
#include <stdio.h>
#include <stdlib.h>
// Define the Node structure
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Head of the list
struct Node* head = NULL;
// Insert at the beginning
void insertAtBeginning(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL)
head->prev = newNode;
head = newNode;
}
// Insert at the end
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
struct Node* temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
// Delete a node by value
void deleteByValue(int key) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
// If head node itself holds the key
if (temp->data == key) {
head = temp->next;
if (head != NULL)
head->prev = NULL;
free(temp);
return;
}
while (temp != NULL && temp->data != key)
temp = temp->next;
if (temp == NULL) {
printf("Node with value %d not found.\n", key);
return;
}
if (temp->next != NULL)
temp->next->prev = temp->prev;
if (temp->prev != NULL)
temp->prev->next = temp->next;
free(temp);
}
// Traverse the list forward
void traverseForward() {
struct Node* temp = head;
printf("Forward: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// Traverse the list backward
void traverseBackward() {
struct Node* temp = head;
if (temp == NULL) {
printf("List is empty.\n");
return;
}
// Go to last node
while (temp->next != NULL)
temp = temp->next;
printf("Backward: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
// Main function to test the operations
int main() {
insertAtBeginning(10);
insertAtEnd(20);
insertAtEnd(30);
insertAtBeginning(5);
traverseForward(); // 5 10 20 30
traverseBackward(); // 30 20 10 5
deleteByValue(20);
traverseForward(); // 5 10 30
deleteByValue(5);
traverseForward(); // 10 30
deleteByValue(100); // Not found
return 0;
}
Comments
Post a Comment