Реализация стека в структуре данных на основе статического массива C++

Рейтинг: 1Ответов: 2Опубликовано: 08.01.2023

Увидел на форме, как одну задачку решили стеком структуре данных через статический массив. Но я не понял, как работает этот стек и его функции. Ну вот к примеру для чего нам нужна переменная int arrayElementsCount = 0 и как она используется в функциях? Можете пожалуйста объяснить этот код.

#include <iostream>
#include <string.h>

#define N 5
using namespace std;
struct WebPage {
    string url;
    int size;
    bool isConnectionSafe;
};

struct Stack {
    WebPage array[N];
    int arrayElementsCount = 0;

    void push(WebPage webPage) {
        if (size() >= N) {
            cout << "Stack is full" << endl;
        }
        else {
            array[arrayElementsCount] = webPage;
            arrayElementsCount++;
        }
    }

    void pop() {
        if (isEmpty()) {
            cout << "Stack is empty" << endl;
        }
        else {
            array[arrayElementsCount - 1] = {};
            arrayElementsCount--;
        }
    }

    bool isEmpty() {
        if (arrayElementsCount == 0) return true;
        else return false;
    }

    int size() {
        return arrayElementsCount;
    }

    void clear() {
        for (int i = size() - 1; i >= 0; i--) {
            array[i] = {};
        }
        arrayElementsCount = 0;
    }

    WebPage top() {
        if (!isEmpty()) {
            return array[arrayElementsCount - 1];
        }
        else {
            cout << "Stack is empty." << endl;
            return { "Null element", 0, false };
        }
    }
};

void print(Stack stack) {
    Stack stackCopy = stack;
    WebPage page;
    for (int i = 0; i < stack.size(); i++) {
        page = stackCopy.top();
        if (page.isConnectionSafe) {
            cout << "Webpage with safe connection: url = " << page.url << " , size is " << page.size << "kb" << endl;
        }
        else
            cout << "Webpage with unsafe connection: url = " << page.url << " , size is " << page.size << "kb" << endl;
        stackCopy.pop();
    }
}

int main() {
    Stack stack;
    WebPage page;
    stack.push({ "google.com", 139, true });
    stack.push({ "youtube.com", 483, true });
    stack.push({ "yabumaga.pl", 9, false });
    stack.push({ "yaraketa.io", 174, false });
    print(stack);
    cout << endl;
    page = stack.top();
    stack.pop();
    page.isConnectionSafe = true;
    stack.push(page);
    print(stack);
    cout << endl;
    stack.push({ "lol.com", 93, false });
    stack.push({ "linkedin.com", 452, true });
    stack.push({ "indianelephant.in", 872, false });
    print(stack);
    cout << endl;
    stack.pop();
    print(stack);
    cout << endl;
    for (int i = 0; i < 5; i++) {
        stack.pop();
    }
    print(stack);
}

Ответы

Ответов пока нет.