fork download
  1. #include <iostream>
  2.  
  3. struct node {
  4. int x;
  5. node *next;
  6. };
  7.  
  8. int countLinkedList(node *n, node **last = NULL) {
  9. int count = 0;
  10. if (last) *last = NULL;
  11. while (n) {
  12. ++count;
  13. if (last) *last = n;
  14. n = n->next;
  15. }
  16. return count;
  17. }
  18.  
  19. node* makeLinkedListNode(int x) {
  20. node *n = new node; // (node*) malloc(sizeof(node));
  21. n->x = x;
  22. n->next = NULL;
  23. return n;
  24. }
  25.  
  26. void freeLinkedList(node *n) {
  27. node *next;
  28. while (n) {
  29. next = n->next;
  30. delete n; // free(n);
  31. n = next;
  32. }
  33. }
  34.  
  35. void copyLinkedList(node *n) {
  36. node *last;
  37. for (int y = countLinkedList(n, &last); y > 0; --y) {
  38. last->next = makeLinkedListNode(n->x);
  39. last = last->next;
  40. n = n->next;
  41. }
  42. }
  43.  
  44. void printLinkedList(node *n) {
  45. while (n) {
  46. std::cout << n->x << " ";
  47. n = n->next;
  48. }
  49. std::cout << std::endl;
  50. }
  51.  
  52. int main() {
  53. node *root = makeLinkedListNode(10);
  54. root->next = makeLinkedListNode(20);
  55. root->next->next = makeLinkedListNode(30);
  56.  
  57. std::cout << "Before copy: ";
  58. printLinkedList(root);
  59.  
  60. copyLinkedList(root);
  61.  
  62. std::cout << "After copy: ";
  63. printLinkedList(root);
  64.  
  65. freeLinkedList(root);
  66. return 0;
  67. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Before copy: 10 20 30 
After copy: 10 20 30 10 20 30