leproza

Double-sided list

Apr 15th, 2022
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <initializer_list>
  3.  
  4. template< typename T >
  5. class MyList
  6. {
  7. protected:
  8.   struct Element
  9.   {
  10.     T value;
  11.     Element* pPrev;
  12.     Element* pNext;
  13.     explicit Element( const T& v ) : value{ v }, pPrev{ nullptr }, pNext{ nullptr } {}
  14.  
  15.     explicit Element( T&& v ) : value{ v }, pPrev{ nullptr }, pNext{ nullptr } {}
  16.   };
  17.   Element* pHead;
  18.   Element* pTail;
  19. public:
  20.   MyList() : pHead{ nullptr }, pTail{ nullptr } {}
  21.   MyList( std::initializer_list<T> list )
  22.   {
  23.     for( const auto& it : list )
  24.     {
  25.       add( it );
  26.     }
  27.   }
  28.   MyList& operator=( MyList&& lst ) noexcept
  29.   {
  30.     pHead = std::move( lst.pHead );
  31.     pTail = std::move( lst.pTail );
  32.     lst.pHead = nullptr;
  33.     lst.pTail = nullptr;
  34.     return *this;
  35.   }
  36.   ~MyList()
  37.   {
  38.     clear();
  39.   }
  40.  
  41.   void clear()
  42.   {
  43.     while( pHead )
  44.     {
  45.       Element* tmp = pHead->pNext;
  46.       delete pHead;
  47.       pHead = tmp;
  48.     }
  49.     pTail = nullptr;
  50.   }
  51.  
  52.   void add( const T& val )
  53.   {
  54.     Element* e = new Element( val );
  55.     if( pHead == nullptr )
  56.     {
  57.       pHead = pTail = e;
  58.       return;
  59.     }
  60.     pTail->pNext = e;
  61.     e->pPrev = pTail;
  62.     pTail = e;
  63.   }
  64.  
  65.   class Iterator
  66.   {
  67.     Element* pE;
  68.   public:
  69.     Iterator( Element* pElement ) : pE{ pElement } {}
  70.     Iterator& operator++()
  71.     {
  72.       pE = pE->pNext;
  73.       return *this;
  74.     }
  75.     bool operator!=( const Iterator& it ) const
  76.     {
  77.       return pE != it.pE;
  78.     }
  79.     T& operator*() { return pE->value; }
  80.   };
  81.  
  82.   Iterator begin() const
  83.   {
  84.     Iterator it( pHead );
  85.     return it;
  86.   }
  87.  
  88.   Iterator end() const
  89.   {
  90.     Iterator it( nullptr );
  91.     return it;
  92.   }
  93. };
  94.  
  95. int main()
  96. {
  97.   MyList<int> l{ 1,2,3,4,5 };
  98.   l.add( 12 );
  99.   int x = 100;
  100.   l.add( std::move( x ) );
  101.   for( const auto& it : l )
  102.   {
  103.     std::cout << it << " ";
  104.   }
  105.   std::cout << std::endl;
  106.  
  107.   MyList< int > l2;
  108.   l2 = std::move(l);
  109.   for( const auto& it : l2 )
  110.   {
  111.     std::cout << it << " ";
  112.   }
  113.   std::cout << std::endl;
  114.  
  115.   return 0;
  116. }
Advertisement
Add Comment
Please, Sign In to add comment