You are on page 1of 6

Program 5

Write a program to implement Double Linked List

#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");

printf("\n\nEnter your choice: ");


scanf("%d", &choice);
switch(choice)
{
case 1:
insertNode();
getch();
break;
case 2:
searchList();
getch();
break;
case 3:
deleteNode();
getch();
break;
case 4:
traverseList();
getch();
break;
case 5:
exit(0);
break;
default:
continue;

}
}
}

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;
}

printf("\nPrinting from first node to last node!!\nList: ");


while(ptr != NULL)
{
if(ptr->next == NULL)
last = ptr;
printf("%d, ", ptr->data);
ptr = ptr->next;
}
printf("\n\nPrinting from last node to first!!\nList: ");
while(last != NULL)
{
printf("%d, ", last->data);
last = last->prev;
}
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;
}

You might also like