Answer to Question #232395 in C for Arup

Question #232395

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.


1
Expert's answer
2021-09-04T10:55:37-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS