Advertisement
NickAndNick

Односвязный список. Обмен первого и последнего

Jun 28th, 2022
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. struct Node {
  5.     string data;
  6.     Node* next;
  7.     Node(const string& line) : data(line), next(nullptr) {}
  8. private:
  9.     friend ostream& operator<<(ostream& out, const Node& node) {
  10.         return out << node.data;
  11.     }
  12. };
  13. class List {
  14. public:
  15.     class Iterator {
  16.     public:
  17.         explicit Iterator(Node* ptr) : curr(ptr) {}
  18.         Iterator& operator++() {
  19.             curr = curr->next;
  20.             return *this;
  21.         }
  22.         string& operator*() {
  23.             return curr->data;
  24.         }
  25.         const string& operator*()const {
  26.             return curr->data;
  27.         }
  28.         Node* operator->() {
  29.             return curr;
  30.         }
  31.         Node* operator->()const {
  32.             return curr;
  33.         }
  34.         bool operator==(const Iterator& iter) {
  35.             return curr == iter.curr;
  36.         }
  37.         bool operator!=(const Iterator& iter) {
  38.             return curr != iter.curr;
  39.         }
  40.     private:
  41.         Node* curr;
  42.     };
  43.     List() : head(nullptr), tail(nullptr) {}
  44.     void add(const string& value) {
  45.         auto node = new Node{ value };
  46.         if (tail) {
  47.             tail->next = node;
  48.             tail = node;
  49.         } else {
  50.             head = tail = node;
  51.         }
  52.     }
  53.     Iterator first() {
  54.         return Iterator(head);
  55.     }
  56.     Iterator last() {
  57.         return Iterator(tail);
  58.     }
  59.     void node_swap(Iterator& a, Iterator& b) {
  60.         iter_swap(a, b);
  61.     }
  62.     Iterator begin()const {
  63.         return Iterator(head);
  64.     }
  65.     Iterator end()const {
  66.         return head != tail ? Iterator(tail->next) : Iterator(tail);
  67.     }
  68. private:
  69.     Node* head;
  70.     Node* tail;
  71. };
  72. void show(const List& list) {
  73.     for (auto& item : list) cout << item << '\n';
  74.     puts("-----");
  75. }
  76. int main() {
  77.     List list;
  78.     list.add("first");
  79.     list.add("...");
  80.     list.add("last");
  81.     show(list);
  82.     auto first = list.first();
  83.     auto last = list.last();
  84.     list.node_swap(first, last);
  85.     show(list);
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement