/*Serial No.138 [swami120.cpp]*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *prev;
struct node *next;
}node;
void create_list(node **head)
{
node *q,*temp;
int ele;
printf("\nEnter the element to be inserted= ");
scanf("%d",&ele);
q=*head;
temp=(node *)malloc(sizeof(node));
if(*head==NULL)
{
temp->info=ele;
temp->next=NULL;
temp->prev=NULL;
*head=temp;
return;
}
else
{
while(q->next!=NULL)
{
q=q->next;
}
temp->info=ele;
temp->next=NULL;
temp->prev=q;
q->next=temp;
}
}
void display_list(node *head)
{
printf("\n");
while(head!=NULL)
{
printf("%d ",head->info);
head=head->next;
}
}
void reverse_display_list(node *head)
{
while(head->next!=NULL)
{
head=head->next;
}
printf("\n\nreverse traversing\n");
printf("%d ",head->info);
do
{
printf("%d ",head->prev->info);
head=head->prev;
}while(head->prev!=NULL);
}
void delete_list(node **head)
{
int flag=1,ele;
node *temp,*q=*head;
printf("\nEnter the element whom u want to delete= ");
scanf("%d",&ele);
if(q->info==ele) /*to delete first node*/
{
temp=q;
*head=temp->next;
temp->next->prev=NULL;
return;
}
while(q!=NULL)
{
if(q->next->info==ele)
{
flag=2;
break;
}
q=q->next;
}
if(flag==1)
printf("\n\No. is not in list.\n");
else
{
temp=q->next;
q->next=q->next->next;
q->next->prev=q;
}
free(temp);
}
void insert_at_position(node *head)
{
int flag=1,ele,num;
node *temp;
printf("\nEnter the element after which u want to insert= ");
scanf("%d",&num);
while(head!=NULL)
{
if(head->info==num)
{
flag=2;
break;
}
head=head->next;
}
if(flag==1)
{
printf("\n\No. is not in list.n");
return;
}
else
{
printf("\nEnter the element to insert= ");
scanf("%d",&ele);
temp=(node *)malloc(sizeof(node));
temp->next=head->next;
temp->prev=head;
temp->info=ele;
temp->next->prev=temp;
head->next=temp;
}
}
void insert_at_beg(node **head)
{
int ele;
printf("\nEnter the element to insert= ");
scanf("%d",&ele);
node *temp;
temp=(node *)malloc(sizeof(node));
temp->info=ele;
temp->next=*head;
temp->prev=NULL;
temp->next->prev=temp;
*head=temp;
}
void main()
{
int choice;
clrscr();
node *start=NULL;
printf("\n\t\t***DOUBLY LINKED LIST***");
printf("\n\t\t------------------------\n\n");
do
{
printf("\n\t[1] Create\\Insert at end.");
printf("\n\t[2] Insert at Position.");
printf("\n\t[3] Insert at Begining.");
printf("\n\t[4] Delete");
printf("\n\t[5] Traverse");
printf("\n\t[6] Traverse in Reverse Direction.");
printf("\n\t[7] Exit");
printf("\nEnter your choice= ");
scanf("%d",&choice);
switch(choice)
{
case 1: create_list(&start);
break;
case 2: insert_at_position(start);
break;
case 3: insert_at_beg(&start);
break;
case 4: delete_list(&start);
break;
case 5: display_list(start);
break;
case 6: reverse_display_list(start);
break;
case 7: exit(0);
}
}while(choice!=7);
getch();
}
Program ain't working when when we choose to insert at beginning in the start
ReplyDelete