fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct ListNode
  5. {
  6. int val;
  7. ListNode *next;
  8. ListNode() : val(0), next(nullptr) {}
  9. ListNode(int x) : val(x), next(nullptr) {}
  10. ListNode(int x, ListNode *next) : val(x), next(next) {}
  11. };
  12.  
  13. ListNode* cloneList(ListNode* head) {
  14. if (!head) return NULL; // <-- add this
  15. ListNode *prev = new ListNode(head->val);
  16. head = head->next;
  17. while (head != NULL)
  18. {
  19. ListNode *p = new ListNode(head->val, prev);
  20. head = head->next;
  21. prev = p;
  22. }
  23. return prev;
  24. }
  25.  
  26. void printList(ListNode* head) {
  27. while (head)
  28. {
  29. cout << head->val << " ";
  30. head = head->next;
  31. }
  32. cout << "\n";
  33. }
  34.  
  35. void freeList(ListNode* head) {
  36. while (head)
  37. {
  38. ListNode *n = head->next;
  39. delete head;
  40. head = n;
  41. }
  42. }
  43.  
  44. int main() {
  45.  
  46. ListNode *head = nullptr;
  47. ListNode **ptr = &head;
  48. for(int i = 1; i <= 5; ++i)
  49. {
  50. *ptr = new ListNode(i);
  51. ptr = &((*ptr)->next);
  52. }
  53.  
  54. printList(head);
  55.  
  56. ListNode *clone = cloneList(head);
  57.  
  58. printList(clone);
  59.  
  60. freeList(head);
  61. freeList(clone);
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5380KB
stdin
Standard input is empty
stdout
1 2 3 4 5 
5 4 3 2 1