Now we see how to create a duplicate of link list. Here we use two link list. First list contains the data to be copied and other will the get the copy of first list.
Algorithm to copy the link list:
The algorithm is used to copy the info part of FROM list to INTO list. As shown below:- Set TEMP = FROM //FROM is same as START of list
- While TEMP != NULL
- Insert the INFO part of TEMP at the last of INTO list
- Set TEMP = TEMP->NEXT
- End While
Function to create the copy of link list:
void copyList(NODE **from, NODE **into){
NODE *temp;
temp = *from;
while(temp != NULL){
insertAtLast(into, temp->info);
temp = temp->next;
}
}
Program to create the copy of link list:
#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 copyList(NODE **, NODE **);
int main(){
NODE *start1 = NULL;
NODE *start2 = NULL;
insertAtLast(&start1, 4);
insertAtLast(&start1, 5);
insertAtLast(&start1, 2);
printf("The nodes of list 1 are : ");
traverse(&start1);
printf("\nThe nodes of list 2 before copying are : ");
traverse(&start2);
copyList(&start1,&start2);
printf("\nThe nodes of list 2 after copying are : ");
traverse(&start2);
return 0;
}
void copyList(NODE **from, NODE **into){
NODE *temp;
temp = *from;
while(temp != NULL){
insertAtLast(into, 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 : 4 5 2 The nodes of list 2 before copying are : The nodes of list 2 after copying are : 4 5 2
Comments
Post a Comment