📍🔥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>34struct Node {5 int data;6 struct Node *next;7};89// Create new node10struct 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}1617// Recursively copy linked list18struct 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}2627// Print list28void printList(struct Node *head) {29 while (head != NULL) {30 printf("%d -> ", head->data);31 head = head->next;32 }33 printf("NULL\n");34}3536int main() {37 // Create original list: 1 -> 2 -> 3 -> 4 -> NULL38 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 list47 struct Node *copy = copyList(head);48 49 printf("Copied list: ");50 printList(copy);51 52 // Modify original to prove copy is independent53 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
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials