fork download
  1. #include<stdio.h>
  2.  
  3. struct node
  4. {
  5. int data;
  6. struct node * next;
  7. };
  8.  
  9. // implementing a function to copy a Linked List
  10. struct node * copyList(struct node * head)
  11. {
  12. // creating a new variable as a list
  13. struct node * list2 = (struct node *)malloc(sizeof(struct node));
  14.  
  15. //creating a temporary variable to traverse the new list
  16. struct node * temp = list2;
  17.  
  18. while(head)
  19. {
  20. // assigning value
  21. temp -> data = head -> data;
  22.  
  23. // move to the next node
  24. head = head -> next;
  25.  
  26. // if the next node exists
  27. // we need to create a new memory space
  28. if(head)
  29. {
  30. struct node * temp2 = (struct node *)malloc(sizeof(struct node));
  31.  
  32. //point the next of the temp to this new location
  33. temp -> next = temp2;
  34.  
  35. // move to the new location
  36. temp = temp -> next;
  37. }
  38. else
  39. {
  40. // since there is no next node
  41. // means end of the list
  42. temp -> next = NULL;
  43. }
  44. }
  45.  
  46. //returning the pointer of the new list
  47. return list2;
  48. }
  49.  
  50. struct node * addElement(struct node *head, int number)
  51. {
  52. struct node * temp = (struct node*)malloc(sizeof(struct node));
  53. temp -> data = number;
  54. temp -> next = NULL;
  55. struct node * temp2 = head;
  56. while(temp2 -> next != NULL)
  57. temp2 = temp2 -> next;
  58. temp2 -> next = temp;
  59. return head;
  60. }
  61.  
  62. // a function to print the list
  63. void printer(struct node * head)
  64. {
  65. while(head)
  66. {
  67. printf("%d ",head -> data);
  68. head = head -> next;
  69. }
  70. }
  71.  
  72. int main(void)
  73. {
  74. //creating a list
  75. struct node * listHead = (struct node*)malloc(sizeof(struct node));
  76. listHead->data = 1;
  77. listHead->next = NULL;
  78. listHead = addElement(listHead, 2);
  79. listHead = addElement(listHead, 3);
  80. listHead = addElement(listHead, 4);
  81.  
  82. printer(listHead);
  83.  
  84. struct node * copy_of_list = copyList(listHead);
  85.  
  86. // print the new list
  87. printf("\n");
  88. printer(copy_of_list);
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
1 2 3 4 
1 2 3 4