Advertisement
35657

Untitled

Mar 16th, 2024 (edited)
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node { // односвязный список состоит из узлов
  6.     int value; // узел хранит информативную часть
  7.     Node* next; // указатель на следующий узел
  8. };
  9.  
  10. class ForwardList {
  11. public:
  12.  
  13.     ForwardList() : size_(0), head_(nullptr) {}
  14.  
  15.     ForwardList(const ForwardList& other) : size_(other.size_), head_(nullptr) {
  16.         if (other.head_ != nullptr) {
  17.             head_ = new Node{ other.head_->value, nullptr };
  18.             Node* temp = head_;
  19.             Node* other_temp = other.head_;
  20.             while (other_temp->next != nullptr) {
  21.                 other_temp = other_temp->next;
  22.                 temp->next = new Node{ other_temp->value, nullptr };
  23.                 temp = temp->next;
  24.             }
  25.         }
  26.     }
  27.  
  28.  
  29.  
  30.     void push_front(const int& value) {
  31.         head_ = new Node{ value, head_ };
  32.         size_++;
  33.     }
  34.  
  35.     void pop_front() {
  36.         if (size_ > 0) {
  37.             Node* temp = head_;
  38.             head_ = head_->next;
  39.             delete temp;
  40.             size_--;
  41.         }
  42.     }
  43.  
  44.     void print() const {
  45.         Node* temp = head_;
  46.         while (temp != nullptr) {
  47.             cout << temp->value << " ";
  48.             temp = temp->next;
  49.         }
  50.         cout << endl;
  51.     }
  52.  
  53.     int size() const {
  54.         return size_;
  55.     }
  56.  
  57. private:
  58.     int size_;
  59.     Node* head_;
  60. };
  61.  
  62. int main() {
  63.  
  64.     ForwardList list1;
  65.     list1.push_front(35);
  66.     list1.push_front(453);
  67.     list1.push_front(357);
  68.  
  69.     list1.print();
  70.     cout << list1.size() << endl;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement