Facebook
From Mateusz, 7 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 262
  1. #include <stdexcept>
  2. #include <iostream>
  3. #include <list>
  4.  
  5. class TrainComposition
  6. {
  7. private:
  8.         std::list<int> trains;
  9. public:
  10.  
  11.         void attachWagonFromLeft(int wagonId)
  12.         {
  13.                 trains.push_front(wagonId);
  14.         }
  15.        
  16.         void attachWagonFromRight(int wagonId)
  17.         {
  18.                 trains.push_back(wagonId);
  19.         }
  20.  
  21.         int detachWagonFromLeft()
  22.         {
  23.                 if (trains.size() == 0)
  24.                         return NULL;
  25.                 auto temp = trains.front();
  26.                 trains.pop_front();
  27.                 return temp;
  28.         }
  29.  
  30.         int detachWagonFromRight()
  31.         {
  32.                 if (trains.size() == 0)
  33.                         return NULL;
  34.                 auto temp = trains.back();
  35.                 trains.pop_back();
  36.                 return temp;
  37.         }
  38. };
  39.  
  40. #ifndef RunTests
  41. int main()
  42. {
  43.         TrainComposition tree;
  44.         tree.attachWagonFromLeft(7);
  45.         tree.attachWagonFromLeft(13);
  46.         std::cout << tree.detachWagonFromRight() << "\n"; // 7
  47.         std::cout << tree.detachWagonFromLeft(); // 13
  48.         return EXIT_SUCCESS;
  49. }
  50. #endif