# Create a Copy of a Linked List

For a given linked list, you are supposed to write a function that creates a copy of the already created linked list.

Example 1:
Input : Linked List : 4 6 2 8 1
Output : Copy of linked list : 4 6 2 8 1

Example 2:
Input : Linked List : 4 5 9 8 2
Output : Copy of linked list : 4 5 9 8 2

Explanation:

• Logic behind this is just create a new node of structure and copy the every existing node to new node.
• Process will continue until the existing list leads to null(recursively).

C program that creates the copy of linked list:

``````#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct node
{
int data;
struct node * next;
};

{
struct node * temp;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
}
}

{

temp1 = (struct node *)malloc(sizeof(struct node));
temp1->next = NULL;
temp1->data = temp->data;
temp1->next = NULL;
temp = temp->next;

while(temp != NULL)
{
temp2 = (struct node *)malloc(sizeof(struct node));
temp2->data = temp->data;
temp1->next = temp2;
temp1 = temp2;
temp = temp->next;
}
printf("\n--------------------------------\n");
printf("Copy of original linked list : ");
}

int main()
{
struct node *head = 0, *newnode, *temp;
int n, choice, newdata;

printf("Enter the number of nodes in the list : ");
scanf("%d", &n);

if(n == 0)
{
printf("--------------------------------\n");
exit(0);
}

for(int i = 1; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data%d : ", i);
scanf("%d", &newnode->data);
newnode->next = 0;
{
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");
}
``````

Output:

``````Enter the number of nodes in the list : 4
Enter the data1 : 3
Enter the data2 : 7
Enter the data3 : 3
Enter the data4 : 8
--------------------------------
Original linked list : 3 7 3 8
--------------------------------
Copy of original linked list : 3 7 3 8
``````