Here we will see how to concat two single link list into other link list. First we copy the content of first list in third list and then the content of second list into third list.
Algorithm for concatenation of two link list:
This algorithm will use three list. List 1 and List 2 will be concatenated into List 3. The step below:- Copy the list 1 into list 3
- Copy the list 2 at the last of list 3
Function to concat two link list:
void concatLists(NODE **start1, NODE **start2, NODE **mergeinto){
NODE *temp;
temp = *start1;
while(temp != NULL){
insertAtLast(&*mergeinto, temp->info);
temp = temp->next;
}
temp = *start2;
while(temp != NULL){
insertAtLast(&*mergeinto, temp->info);
temp = temp->next;
}
}
Program to concat two link lists:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
void insertAtLast(NODE **, int);
void traverse(NODE **);
void concatLists(NODE **, NODE **, NODE **);
int main(){
NODE *start1 = NULL;
NODE *start2 = NULL;
NODE *start3 = NULL;
insertAtLast(&start1, 10);
insertAtLast(&start1, 52);
insertAtLast(&start1, 88);
insertAtLast(&start2 ,9);
insertAtLast(&start2, 0);
insertAtLast(&start2, 5);
printf("\nThe nodes of list 1 are : ");
traverse(&start1);
printf("\nThe nodes of list 2 are : ");
traverse(&start2);
concatLists(&start1, &start2, &start3);
printf("\nThe nodes of list 3 after concat of list are : ");
traverse(&start3);
return 0;
}
void concatLists(NODE **start1, NODE **start2, NODE **mergeinto){
NODE *temp;
temp = *start1;
while(temp != NULL){
insertAtLast(&*mergeinto, temp->info);
temp = temp->next;
}
temp = *start2;
while(temp != NULL){
insertAtLast(&*mergeinto, temp->info);
temp = temp->next;
}
}
void insertAtLast(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
NODE *temp = *start;
ptr->info = info;
ptr->next = NULL;
if(*start == NULL){
*start = ptr;
}
else
{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = ptr; //last node point to new node ptr
}
}
void traverse(NODE **start){
NODE *temp;
temp = *start;
while(temp != NULL){
printf("%d ", temp->info);
temp = temp->next;
}
}
The nodes of list 1 are : 10 52 88 The nodes of list 2 are : 9 0 5 The nodes of list 3 after concat of list are : 10 52 88 9 0 5
Comments
Post a Comment