World's most popular travel blog for travel bloggers.

Write an algorithm for the implementation of a Circularly Doubly Linked List

, , No Comments

 

#include<stdio.h>
/* Structure declaration */
struct LinkedList
{
struct LinkedList *previous;
int number;
struct LinkedList *next;
};
typedef struct LinkedList NODE;

/* Global variable declaration */
NODE *head, *temp, *p;

/* Global functions declaration */
void insertNode(int n);
void deleteNode(int n);
void displayList();

/* main( ) function */
void main()
{
int choice, num;
while(1)
{
printf("\n Press 1 for insert number");
printf("\n Press 2 for delete number");
printf("\n Press 3 for display list");
printf("\n Press 4 for exit");
printf("\n Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter the number : ");
scanf("%d",&num);
insertNode(num);
break;
case 2:
if(head == NULL)
printf("\n List is blank !");
else
{
printf("\n Enter the number : ");
scanf("%d",&num);
deleteNode(num);
}
break;
case 3:
displayList();
break;
case 4:
exit(0);
default:
printf("\n\n\n Wrong Input");
}
}
}

/* Insert number into the list */
void insertNode(int n)
{
/* Check whether the list is blank or not */
/* If blank then create a memory into head variable and place the number into it */
if(head == NULL)
{
head = (NODE *) malloc(sizeof(NODE));
head->number = n;
head->previous = head;
head->next = head;
}
else
{
/* If the list is not blank then create a memory into temp variable, place the number into it and add this memory to the end of the list */
temp = (NODE *) malloc(sizeof(NODE));
temp->number = n;
p = head;
while(p->next != head)
p = p->next;
p->next = temp;
temp->previous = p;
temp->next = head;
head->previous = temp;
}
}

/* Delete a particular number from the list */
void deleteNode(int n)
{
int found = 0;
/* Check whether the list contain only one element or not */
if(head->next == head && head->previous == head)
{
if(head->number == n)
{
found = 1;
head = NULL;
}
}
else
/* Check whether the number found into the first-memory (head) of the list or not ? */
if(head->number == n)
{
temp = head;
head = head->next;
head->previous = temp->previous;
temp->previous->next = head;
found = 1;
}
else
{
p = head->next;
while(p != head)
{
if(p->number == n)
{
p->next->previous = p->previous;
p->previous->next = p->next;
found = 1;
break;
}
p = p->next;
}
}
if(found == 0)
printf("\n Element not found !");
}

/* Display list elements */
void displayList()
{
/* Check whether the list is blank or not */
if(head == NULL)
printf("\n List is blank !");
else
{
p = head;
while(p->next != head)
{
printf("\t%d",p->number);
p = p->next;
}
printf("\t%d",p->number);
}
}

0 comments:

Post a Comment

Let us know your responses and feedback