1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- #include "MyList.h"
- #include <iostream>
- MyList::MyList(std::initializer_list<int> il)
- :pHead(nullptr)
- {
- auto iter = il.end();
- iter--;
- for (int i = 0; i < il.size(); i++)
- {
- addToHead(*iter);
- iter--;
- }
- }
- MyList::MyList(MyList& other)
- :pHead(nullptr)
- {
- pHead = new ListNode(other.pHead->val);
- ListNode* prev = pHead;
- ListNode* cur = pHead;
- ListNode* pOtherCur = other.pHead->next;
- while (pOtherCur)
- {
- cur = new ListNode(pOtherCur->val);
- prev->next = cur;
-
- pOtherCur= pOtherCur->next;
- prev = cur;
- }
- }
- MyList::~MyList()
- {
- if (pHead)
- {
- ListNode* tmp = pHead->next;
- while (pHead)
- {
- delete pHead;
- pHead = tmp;
- if(pHead)tmp = tmp->next;
- }
- }
- };
- void MyList::addToHead(int val) {
- ListNode* curr = new ListNode(val);
- curr->next = pHead;
- pHead = curr;
- }
- void MyList::print()
- {
- ListNode* first = pHead;
-
- while (first)
- {
- std::cout << &first->val << " " << first->val << " ";
- first = first->next;
- }
- std::cout << std::endl;
- }
|