Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cassert>
- #include <memory>
- template <typename T>
- class Node
- {
- std::shared_ptr<Node<T>> nextnode;
- T value;
- public:
- Node() {}
- Node(T v) : value(v), nextnode(nullptr) {}
- Node(T v, std::shared_ptr<Node<T>> n) : value(v), nextnode(n) {}
- auto get() const noexcept -> decltype(value)
- {
- return value;
- }
- auto next() const noexcept -> decltype(nextnode)
- {
- return nextnode;
- }
- };
- template <typename T>
- class Stack
- {
- std::shared_ptr<Node<T>> head;
- public:
- Stack() : head(nullptr) {}
- void push(T v)
- {
- auto aux = std::make_shared<Node<T>>(Node<T>(v, head));
- head = aux;
- }
- auto pop() -> decltype(head.get()->get())
- {
- if(empty()) return 0;
- auto aux = head;
- head = head->next();
- return aux.get()->get();
- }
- bool empty()
- {
- return head == nullptr;
- }
- template <typename F>
- void apply(F f)
- {
- for(auto aux = head; aux; aux = aux->next())
- f(aux.get()->get());
- }
- };
- int main() {
- Stack<int> s;
- s.push(10);
- s.push(15);
- s.apply([](int s) { std::cout << s << std::endl; });
- assert(s.pop() == 15);
- assert(s.pop() == 10);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement