Untitled
unknown
c_cpp
2 years ago
1.2 kB
3
Indexable
#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; }
Editor is loading...