Advertisement
awsmpshk

List.cpp

Apr 14th, 2020
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. template <typename T>
  7. class List
  8. {
  9.  
  10.     struct Item
  11.     {
  12.         T inf;
  13.         Item* next;
  14.         Item(T x, Item* ref = nullptr) : inf(x), next(ref) {}
  15.     } *first = nullptr, *last = nullptr;
  16.  
  17. public:
  18.     List() = default;
  19.  
  20.     // конструктор копирования
  21.     List(const List &other)
  22.     {
  23.         for (Item *t = other.first; t != nullptr; t = t->next)
  24.         {
  25.             this->add(t->inf);
  26.         }
  27.     }
  28.  
  29.     void add(T x)
  30.     {
  31.         Item *item = new Item(x);
  32.         if (last != nullptr)
  33.             last->next = item;
  34.         last = item;
  35.         if (first == nullptr)
  36.             first = last;
  37.     }
  38.  
  39.     void print()
  40.     {
  41.         for (Item* t = first; t != nullptr; t = t->next)
  42.             cout << t->inf << " ";
  43.         cout << endl;
  44.     }
  45.  
  46.     void doubleOdd()
  47.     {
  48.     for (Item* t = first; t != nullptr; t = t->next)
  49.         {
  50.             if (t->inf % 2 == 0)
  51.             {
  52.                 Item *newItem = new Item(t->inf, t->next);
  53.                 t->next = newItem;
  54.         t = t->next;
  55.             }
  56.         }
  57.     }
  58.  
  59.     // создание нового списка, в котором удалены элементы, следующие после x
  60.     List getListDelAfterX(T x)
  61.     {
  62.         List *newList = new List();
  63.         if (first != nullptr)
  64.         {
  65.             newList->add(first->inf);
  66.             for (Item *t = first; t -> next != nullptr; t = t -> next)
  67.             {
  68.                 if (t->inf != x)
  69.                 {
  70.                     newList->add(t->next->inf);
  71.                 }
  72.             }
  73.         }
  74.         return *newList;
  75.     }
  76.  
  77.     // перенос списка в поток вывода
  78.     friend ostream& operator<<(ostream& out, const List<T> &lst)
  79.     {
  80.         for (Item* t = lst.first; t->next != nullptr; t = t->next)
  81.         {
  82.             out << t->inf << " -> ";
  83.         }
  84.         if (lst.last != nullptr)
  85.         {
  86.             out << lst.last->inf;
  87.         }
  88.         return out;
  89.     }
  90. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement