Here is another program on linked list. The following program will create two separate linked list and then the second list will be appended at the end of the first linked list .
#include < stdio.h >
#include < stdlib.h >
#include< string.h >
struct link
{
char data[30];
struct link *next;
};
struct link *node;
void display(struct link *n)
{
node=n;
while (node)
{
printf(" %s\n", node->data);
node = node->next;
}
}
void create(struct link *n)
{
int i = 1;
char ch='y';
node=n;
printf("\n Enter the String- %d:- ", (i+1));
scanf("%s", &node->data);
while(ch != 'n')
{
node->next = (struct link * ) malloc(sizeof(struct link));
node = node->next;
node->next = NULL;
fflush(stdin);
printf("\n Enter the String- %d:- ", (i+1));
scanf("%s", &node->data);
fflush(stdin);
printf("\n Enter choice--'n' for break: ");
ch = getche();
i ++;
}
printf("\n Total nodes = %d", i);
}
void join(struct link *one, struct link *two, struct link *three)
{
while(one)
{
strcpy(three->data,one->data);
one = one->next;
three->next = (struct link* ) malloc(sizeof(struct link));
three = three->next;
}
while(two)
{
strcpy(three->data,two->data);
two = two->next;
three->next = (struct link*)malloc(sizeof(struct link));
three = three->next;
}
three->next = NULL;
}
void main()
{
struct link *one, *two, *three;
one = (struct link *)malloc(sizeof(struct link));
two = (struct link *)malloc(sizeof(struct link));
three = (struct link *)malloc(sizeof(struct link));
clrscr();
printf("Creating First linked list.\n");
create(one);
printf("\n Original list ONE is as follows:\n");
display(one);
printf("\nCreating Second linked list.\n");
create(two);
printf("\n Original list TWO is as follows:\n");
display(two);
join(one,two,three);
printf("\n Original list ONE + TWO is as follows:\n");
display(three);
getch();
}
Technical analysis of this appending linked list program
Three list pointers are used in this linked list program. All the pointers are assigned address of three separate locations ( values are not assigned) and this is done in the main () function. User defined function ‘void create(struct link*)’ is used to create the two separate linked lists. Another function defined in this program ‘void display(struct link*)’ is used to display the linked lists separately. Appending the linked lists are done by function ‘void join(struct link*, struct link*, struct link*)’
No comments:
Post a Comment