35657

Untitled

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