DOUBLY LINKED LIST PROGRAM USING C LANGUAGE
This
program is about creation and display of “doubly linked list”.
As
we know linked is type of data structure whose node is connected by pointer
data type. Doubly linked list a type of linked list which contain the address
of the previous and next node, which is
one of the most special characteristic of this linked list.
The
program starts with the two header file header file that is
“#include<stdio.h>” which contain input and output function like
printf(), scanf() etc. And the second is “#include<conio.h>” which
contain clrscr(), getch(), etc type of functions.
Then
we have to make structure for the node of linked list. As in program “typedef
struct” is use because “typedef” is keyword which is use to rename the
structure as a short name which makes our program easier. Now we don’t need to
write “typedef struct list” we can just write “node”.
As
we know doubly linked list contain two pointer previous and next therefore we
have taken “*pre” of struct list type to contain the previous node address,
then we have taken the variable “data” of integer type and then we have taken
“*next” of struct list type, which contain the address of next node.
#include<stdio.h>
#include<conio.h>
typedef struct list
{
struct list *pre;
int data ;
struct list *next;
}node;
node *start=NULL;
void create();
void display(node*);
void main()
{
// node *ptr=NULL;
int option;
clrscr();
do
{
printf("\n main menu\n");
printf("1: create list\n");
printf("2: display list\n");
printf("0: exit \n");
printf("\n enter your option");
scanf("%d",&option);
switch(option)
{
case 1: create();
printf("\n linked list created->");
break;
case 2: display(start);
case 0:
exit (0);
}
}while(option!=0);
getch();
}
void create()
{
node *ptr=NULL, *nnode=NULL;
char ans;
int num;
do{
nnode=(node*)malloc (sizeof(node));
printf("\n enter data");
scanf("%d",&num);
nnode->data=num;
if(start==NULL)
{
start->pre=NULL;
start->next=nnode;
nnode->pre=start;
nnode->next=NULL;
start=nnode;
}
else
{
ptr=start;
while (ptr->next!=NULL)
ptr=ptr->next;
ptr->next=nnode;
ptr->pre=ptr;
nnode->next=NULL;
}
printf("\n do you want to add more node (Y/N)");
ans=getche();
}while(ans=='Y'||ans=='y');
}
void display(node *start)
{
node*ptr=NULL;
ptr=start;
while(ptr!=NULL)
{
printf("\t%d->",ptr->data);
ptr=ptr->next;
}
getch();
}
Post a Comment