Untitled

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
1.2 kB
1
Indexable
Never
#include <iostream>

struct Node {
    int val;
    Node *next;
};

struct Stack {
    Node *head;

    void push(int value) {
        Node new_head = Node({value, this->head});
        this->head = &new_head;
    }

    int pop() {
        if (!this->head) {
            throw std::invalid_argument("nothing to pop");
        }
        auto current_peek_value = this->head->val;
        this->head = this->head->next;
        return current_peek_value;
    }

    [[nodiscard]] int top() const {
        if (this->head) {
            return this->head->val;
        }
        return 0;
    }

    void print() const {
        auto current_head = this->head;
        while (current_head) {
            if (current_head->next) {
                std::cout << current_head->val << "-> ";
            } else {
                std::cout << current_head->val;
            }

            current_head = current_head->next;
        };
        std::cout << std::endl;
    }
};

int main() {
    auto stack = Stack({});
//    stack.push(10);
//    stack.push(10);
    stack.print();
//    stack.pop();
//    std::cout << stack.peek() << std::endl;

    return 0;
}