Write a menu driven program to perform the following operations in a double linked list by
using suitable user defined functions for each case.
a) Traverse the list forward
b) Traverse the list backward
c) Check if the list is empty
d) Insert a node at the certain position (at beginning/end/any position)
e) Delete a node at the certain position (at beginning/end/any position)
f) Delete a node for the given key
g) Count the total number of nodes
h) Search for an element in the linked list
Verify & validate each function from main method.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *nextNode;
};
struct Node *headNode = NULL;
struct Node *currentNode = NULL;
//Traversing the linked list forward
void traverseBackward(struct Node *listNode) {
if(listNode == NULL) {
printf("[null] => ");
return;
}
traverseBackward(listNode->nextNode);
printf(" %d =>",listNode->data);
}
void forward(struct Node *listNode){
if(listNode==NULL){
printf("[null] =>");
}
while(listNode != NULL){
printf("%d =>", listNode->data);
listNode = listNode->nextNode;
}
}
//Creating a Linked List
void insertElement(int data) {
struct Node *linkNode = (struct Node*) malloc(sizeof(struct Node));
linkNode->data = data;
linkNode->nextNode = NULL;
if(headNode==NULL) {
headNode = linkNode;
return;
}
currentNode = headNode;
while(currentNode->nextNode!=NULL)
currentNode = currentNode->nextNode;
currentNode->nextNode = linkNode;
}
int isEmpty(struct Node * list){
if(list==NULL){
return 1;
}
else{
return 0;
}
}
int main() {
insertElement(1);
insertElement(2);
insertElement(3);
insertElement(4);
insertElement(5);
insertElement(6);
int n;
printf("1. Enter 1 to traverse the linked list forward\n");
printf("2. Enter 2 to traverse the linked list backward\n");
printf("3. Enter 3 to check if the linked list is empty\n");
scanf("%d", &n);
if(n==1){
printf("Traversing the linked list forward\n");
forward(headNode);
}
else if(n==2){
printf("\nTraversing the linked list backward\n");
traverseBackward(headNode);
}
else if(n==3){
if(isEmpty(headNode)==1){
printf("\nThe linked list is empty\n");
}
else{
printf("\nThe linked list is not empty\n");
}
}
return 0;
}
Comments
Leave a comment