Iterator

 avatar
Alexmegawin
c_cpp
a year ago
2.1 kB
1
Indexable
Never
#include <iostream>
using namespace std;

class List
{
private:
    class Node
    {
        friend class List;
        friend class Iterator;
    public:
        Node(int value)
        {
            this->value = value;
            this->next_node = nullptr;
        }
        Node(int value, Node* next_node)
        {
            this->value = value;
            this->next_node = next_node;
        }
    private:
        int value;
        Node* next_node;
    };

public:
    class Iterator
    {
    public:
        Iterator(Node* current)
        {
            this->current = current;
        }
    private:
        Node* current;
    public:
        int getValue()
        {
            return current->value;
        }
        void goNext()
        {
            current = current->next_node;
        }
    };
     
public:
    List()
    {
        head = nullptr;
        lenght = 0;
    }
private:
    Node* head;
    int lenght;
public:
    Iterator begin()
    {
        Iterator iterator(head);
        return iterator;
    }
    void addToHead(int value)
    {
        Node* new_head = new Node(value, head);
        head = new_head;
        lenght++;
    }

    bool deleteFromHead(int* result)
    {
        if (lenght == 0)
        {
            return false;
        }

        Node* pre_head = head;
        head = head->next_node;

        *result = pre_head->value;

        delete pre_head;
        lenght--;

        return true;
    }

    void printList()
    {
        Node* current = head;
        while (current != nullptr)
        {
            cout << current->value << " ";
            current = current->next_node;
        }
    }

};

int main() {
    List list;
    for (int i = 0; i < 5; i++)
    {
        list.addToHead(i);
    }

    list.printList();

    cout << endl;

    List::Iterator iterator = list.begin();

    for (int i = 0; i < 5; i++)
    {
        cout << iterator.getValue() << " ";
        iterator.goNext();
    }

    return 0;
}