MyList.cpp 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "MyList.h"
  2. #include <iostream>
  3. MyList::MyList(std::initializer_list<int> il)
  4. :pHead(nullptr)
  5. {
  6. auto iter = il.end();
  7. iter--;
  8. for (int i = 0; i < il.size(); i++)
  9. {
  10. addToHead(*iter);
  11. iter--;
  12. }
  13. }
  14. MyList::MyList(MyList& other)
  15. :pHead(nullptr)
  16. {
  17. pHead = new ListNode(other.pHead->val);
  18. ListNode* prev = pHead;
  19. ListNode* cur = pHead;
  20. ListNode* pOtherCur = other.pHead->next;
  21. while (pOtherCur)
  22. {
  23. cur = new ListNode(pOtherCur->val);
  24. prev->next = cur;
  25. pOtherCur= pOtherCur->next;
  26. prev = cur;
  27. }
  28. }
  29. MyList::~MyList()
  30. {
  31. if (pHead)
  32. {
  33. ListNode* tmp = pHead->next;
  34. while (pHead)
  35. {
  36. delete pHead;
  37. pHead = tmp;
  38. if(pHead)tmp = tmp->next;
  39. }
  40. }
  41. };
  42. void MyList::addToHead(int val) {
  43. ListNode* curr = new ListNode(val);
  44. curr->next = pHead;
  45. pHead = curr;
  46. }
  47. void MyList::print()
  48. {
  49. ListNode* first = pHead;
  50. while (first)
  51. {
  52. std::cout << &first->val << " " << first->val << " ";
  53. first = first->next;
  54. }
  55. std::cout << std::endl;
  56. }