Saturday, January 16, 2021

Write a C program to copy one linked list to another and count the number of node

 # include <stdio.h>
# include <stdlib.h>
struct list
{
char info[20];
struct list *next;
struct list *prev;
};
struct list *new1,*node;
void create(struct list *s,struct list *e)
{
char ch;
node=s;
printf("\nWant to create a node(y/n):");
ch=getche();
while (ch != 'n')
{
node->next = (struct list *) malloc(sizeof(struct list));
node->next->prev= node;
node = node->next;
printf("\n Enter the string value:- ");
gets(node->info);
node->next = e;
e->prev=node;
printf("\n Enter choice--'n' for break: ");
ch = getche();
}
}
void displayL (struct list *s,struct list *e)
{
node = s->next;
while (node!=e)
{
printf(" %u--%s", node,node->info);
node = node->next;
}
printf("\n");
}
void displayR (struct list *e,struct list *s)
{
node = e->prev;
while (node!=s)
{
printf("  %s",node->info);
node = node->prev;
}
printf("\n");
}
void merge(struct list *s,struct list *e, struct list *s1,struct list *e1)
{
int i=0;
s=s->next;

while(s!=e)
{
s1->next=(struct list*)malloc(sizeof(struct list));
s1->next->prev=s1;
s1=s1->next;
 strcpy(s1->info,s->info);
 s=s->next;
 s1->next=e1;
e1->prev=s1;

 i++;
}
printf("\nNumber of Nodes: %d",i);
}
void main()
{
struct list *start,*end,*start1,*end1;
clrscr();
start= (struct list *) malloc(sizeof(struct list));
start->next=NULL;
end= (struct list *) malloc(sizeof(struct list));
end->next=NULL;
start1= (struct list *) malloc(sizeof(struct list));
start1->next=NULL;
end1= (struct list *) malloc(sizeof(struct list));
end1->next=NULL;
create(start,end);
printf("\n Created list is as follows(L ->R)\n");
displayL(start,end);
printf("\n Created list displayed from R->L\n");
displayR(end,start);
merge(start,end,start1,end1);
printf("\n Copied List from L ->R\n");
displayL(start1,end1);
printf("\n list from R to L after deletion\n");
displayR(end1,start1);

getch();

}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner