Programs On Doubbly Linked List
Programs On Doubbly Linked List
1.Create a Doubly linked List ,count the node and display the contents of the node
,search the element in the list.
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node *prev;
int data;
struct node *next;
}*new,*head=NULL,*temp;
int main()
{
int val,in,count=0,flag=0,key;
do{
new=(struct node *)malloc(sizeof(struct node));
new->prev=NULL;
printf("enter the value\n");
scanf("%d",&val);
new->data=val;
new->next=NULL;
if(head==NULL){
head=new;
temp=new;
}
else{
temp->next=new;
new->prev=temp;
temp=new;
}
printf("Do you want to add one more node 1-Yes/0-No\n");
scanf("%d",&in);
}while(in);
count=0;
temp=head;
printf("\n Elements in doubly linked list are :\n");
while(temp!=NULL){
count=count+1;
printf("%d<->",temp->data);
temp=temp->next;
}
printf("\nTotal number of nodes in the list are=%d\n",count);
//search the Key element in the list
printf("enter the Key element\n");
scanf("%d",&key);
temp=head;
while(temp!=NULL && temp->data!=key)
{
temp=temp->next;
}
if(temp->data==key)
printf("Key element is found\n");
else
printf("key element is not found\n");
}
2. Traverse the list in forward direction and reverse direction
Function:
if (head == NULL) {
printf("The list is empty.\n");
return;
}
temp=head;
printf("Forward traversal:\n");
while (temp != NULL) {
printf("%d<->", temp->data);
curr = temp; // Save the last node in curr
temp = temp->next;
}
printf("NULL\n");
if (head != NULL)
head->prev = new;
head = new;
//Traverse the list
temp=head;
while(temp!=NULL)
{
printf("%d<->",temp->data);
temp=temp->next;
}
}
// Update the last node's next pointer and set the new node's previous pointer
temp->next = new;
new->prev = temp;
if (temp->next != NULL) {
temp->next->prev = new;
}
temp->next = new;
printf("Node inserted at position %d.\n", pos);
}
if(d->next!=NULL){
d->next->prev = temp;
}
d->prev=NULL;
// Free the deleted node
free(d);
}
temp = head;
while (temp != NULL) {
printf("%d<->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to display all the elements in the doubly linked list
void Display() {
int count=0;
temp = head;
if (head == NULL) {
printf("List is empty\n");
return;
}
printf("\n1-Insert_Begin\t2-Insert_End\t3-Display\n4-Insert_SpecifiedPos\t5-Delete_Begin\t6
-Delete_End\t7-Delete_SpecifiedPos\t8-Exit");
printf("\nEnter your choice\n");
scanf("%d", &ch);
switch (ch) {
case 1:Insert_Begin();
break;
case 2:Insert_End();
break;
case 3:Display();
break;
case 4:Insert_SpecifiedPos();
break;
case 5:Delete_Begin();
break;
case 6:Delete_End();
break;
case 7:Delet_SpecifiedPos();
break;
case 8:exit(0);
break;
default:printf("Invalid choice\n");
break;
}
}
return 0;
}