Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <initializer_list>
- template< typename T >
- class MyList
- {
- protected:
- struct Element
- {
- T value;
- Element* pPrev;
- Element* pNext;
- explicit Element( const T& v ) : value{ v }, pPrev{ nullptr }, pNext{ nullptr } {}
- explicit Element( T&& v ) : value{ v }, pPrev{ nullptr }, pNext{ nullptr } {}
- };
- Element* pHead;
- Element* pTail;
- public:
- MyList() : pHead{ nullptr }, pTail{ nullptr } {}
- MyList( std::initializer_list<T> list )
- {
- for( const auto& it : list )
- {
- add( it );
- }
- }
- MyList& operator=( MyList&& lst ) noexcept
- {
- pHead = std::move( lst.pHead );
- pTail = std::move( lst.pTail );
- lst.pHead = nullptr;
- lst.pTail = nullptr;
- return *this;
- }
- ~MyList()
- {
- clear();
- }
- void clear()
- {
- while( pHead )
- {
- Element* tmp = pHead->pNext;
- delete pHead;
- pHead = tmp;
- }
- pTail = nullptr;
- }
- void add( const T& val )
- {
- Element* e = new Element( val );
- if( pHead == nullptr )
- {
- pHead = pTail = e;
- return;
- }
- pTail->pNext = e;
- e->pPrev = pTail;
- pTail = e;
- }
- class Iterator
- {
- Element* pE;
- public:
- Iterator( Element* pElement ) : pE{ pElement } {}
- Iterator& operator++()
- {
- pE = pE->pNext;
- return *this;
- }
- bool operator!=( const Iterator& it ) const
- {
- return pE != it.pE;
- }
- T& operator*() { return pE->value; }
- };
- Iterator begin() const
- {
- Iterator it( pHead );
- return it;
- }
- Iterator end() const
- {
- Iterator it( nullptr );
- return it;
- }
- };
- int main()
- {
- MyList<int> l{ 1,2,3,4,5 };
- l.add( 12 );
- int x = 100;
- l.add( std::move( x ) );
- for( const auto& it : l )
- {
- std::cout << it << " ";
- }
- std::cout << std::endl;
- MyList< int > l2;
- l2 = std::move(l);
- for( const auto& it : l2 )
- {
- std::cout << it << " ";
- }
- std::cout << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment