fork(1) 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. ListNode *prev = new ListNode(head->val);
  15. head = head->next;
  16. while (head != NULL)
  17. {
  18. ListNode *p = new ListNode(head->val, prev);
  19. head = head->next;
  20. prev = p;
  21. }
  22. return prev;
  23. }
  24.  
  25. void printList(ListNode* head) {
  26. while (head)
  27. {
  28. cout << head->val << " ";
  29. head = head->next;
  30. }
  31. cout << "\n";
  32. }
  33.  
  34. void freeList(ListNode* head) {
  35. while (head)
  36. {
  37. ListNode *n = head->next;
  38. delete head;
  39. head = n;
  40. }
  41. }
  42.  
  43. int main() {
  44.  
  45. ListNode *head = nullptr;
  46. ListNode **ptr = &head;
  47. for(int i = 1; i <= 5; ++i)
  48. {
  49. *ptr = new ListNode(i);
  50. ptr = &((*ptr)->next);
  51. }
  52.  
  53. printList(head);
  54.  
  55. ListNode *clone = cloneList(head);
  56.  
  57. printList(clone);
  58.  
  59. freeList(head);
  60. freeList(clone);
  61. return 0;
  62. }
Success #stdin #stdout 0.01s 5548KB
stdin
Standard input is empty
stdout
1 2 3 4 5 
5 4 3 2 1