Professional Documents
Culture Documents
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
struct node* prev;
}*head;
void insertNode();
void deleteNode();
void searchList();
void traverseList();
void main()
{
head = NULL;
int choice;
while(1)
{
clrscr();
printf("1. Create a node");
printf("\n2. Search node in list");
printf("\n3. Delete a node");
printf("\n4. Traverse the list");
printf("\n5. EXIT");
}
}
}
void insertNode()
{
int data;
printf("\n\nEnter data: ");
scanf("%d", &data);
struct node*temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
if(head == NULL)
{
head = temp;
return;
}
struct node*ptr = head;
while(ptr -> next != NULL)
ptr = ptr->next;
ptr->next = temp;
temp->prev = ptr;
return;
}
void traverseList()
{
struct node* ptr = head;
struct node* last = NULL;
if(head == NULL)
{
printf("\n\nList already empty!!");
return;
}
void deleteNode()
{
struct node*ptr = head;
int data, pos, i = 1, last = 0;
if(head == NULL)
{
printf("\n\nList already empty!!");
return;
}
printf("\n\nEnter the position of the element to delete: ");
scanf("%d", &pos);
while(ptr->next != NULL)
{
ptr = ptr->next;
i++;
}
last = i;
if(pos > i)
{
printf("\n\nInvalid position!");
return;
}
i = 1;
ptr = head;
while(i != pos)
{
ptr = ptr->next;
i++;
}
if((pos == 1 || last == 1) && last > 1)
ptr->next->prev = NULL;
else if(pos == 1 && last == 1)
head = NULL;
else if(pos == last)
ptr->prev->next = NULL;
else
{
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
}
free(ptr);
printf("\nDeleted node at position: %d", pos);
return;
}
void searchList()
{
int data, found = 0, pos = 1;
printf("\n\nEnter item to search for: ");
scanf("%d", &data);
struct node* ptr = head;
while(ptr != NULL)
{
if(ptr->data == data)
{
found = 1;
break;
}
ptr = ptr->next;
pos++;
}
if(found == 1)
printf("\nItem found at position: %d", pos);
else
printf("\nItem not found!");
return;
}