📍🔥Advanced

Create Copy of Singly Linked List

Copy linked list recursively

Create a copy of a singly linked list using recursion.

Program Code

copy_linked_list.c
C
1#include <stdio.h>
2#include <stdlib.h>
3
4struct Node {
5 int data;
6 struct Node *next;
7};
8
9// Create new node
10struct Node* createNode(int data) {
11 struct Node *node = (struct Node*)malloc(sizeof(struct Node));
12 node->data = data;
13 node->next = NULL;
14 return node;
15}
16
17// Recursively copy linked list
18struct Node* copyList(struct Node *head) {
19 if (head == NULL) return NULL;
20
21 struct Node *newNode = createNode(head->data);
22 newNode->next = copyList(head->next);
23
24 return newNode;
25}
26
27// Print list
28void printList(struct Node *head) {
29 while (head != NULL) {
30 printf("%d -> ", head->data);
31 head = head->next;
32 }
33 printf("NULL\n");
34}
35
36int main() {
37 // Create original list: 1 -> 2 -> 3 -> 4 -> NULL
38 struct Node *head = createNode(1);
39 head->next = createNode(2);
40 head->next->next = createNode(3);
41 head->next->next->next = createNode(4);
42
43 printf("Original list: ");
44 printList(head);
45
46 // Copy list
47 struct Node *copy = copyList(head);
48
49 printf("Copied list: ");
50 printList(copy);
51
52 // Modify original to prove copy is independent
53 head->data = 100;
54 printf("\nAfter modifying original:\n");
55 printf("Original: ");
56 printList(head);
57 printf("Copy: ");
58 printList(copy);
59
60 return 0;
61}
Output

Original list: 1 -> 2 -> 3 -> 4 -> NULL

Copied list: 1 -> 2 -> 3 -> 4 -> NULL

 

After modifying original:

Original: 100 -> 2 -> 3 -> 4 -> NULL

Copy: 1 -> 2 -> 3 -> 4 -> NULL