Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <memory>
  4.  
  5. template <typename T>
  6. class Node
  7. {
  8.     std::shared_ptr<Node<T>> nextnode;
  9.     T value;
  10.  
  11. public:
  12.     Node() {}
  13.     Node(T v) : value(v), nextnode(nullptr) {}
  14.     Node(T v, std::shared_ptr<Node<T>> n) : value(v), nextnode(n) {}
  15.  
  16.     auto get() const noexcept -> decltype(value)
  17.     {
  18.         return value;
  19.     }
  20.  
  21.     auto next() const noexcept -> decltype(nextnode)
  22.     {
  23.         return nextnode;
  24.     }
  25.  
  26. };
  27.  
  28. template <typename T>
  29. class Stack
  30. {
  31.     std::shared_ptr<Node<T>> head;
  32.  
  33. public:
  34.     Stack() : head(nullptr) {}
  35.  
  36.     void push(T v)
  37.     {
  38.         auto aux = std::make_shared<Node<T>>(Node<T>(v, head));
  39.         head = aux;
  40.     }
  41.  
  42.     auto pop() -> decltype(head.get()->get())
  43.     {
  44.         if(empty()) return 0;
  45.         auto aux = head;
  46.         head = head->next();
  47.         return aux.get()->get();
  48.     }
  49.  
  50.     bool empty()
  51.     {
  52.         return head == nullptr;
  53.     }
  54.  
  55.     template <typename F>
  56.     void apply(F f)
  57.     {
  58.         for(auto aux = head; aux; aux = aux->next())
  59.             f(aux.get()->get());
  60.     }
  61.  
  62. };
  63.  
  64. int main() {
  65.     Stack<int> s;
  66.  
  67.     s.push(10);
  68.     s.push(15);
  69.  
  70.     s.apply([](int s) { std::cout << s << std::endl; });
  71.    
  72.     assert(s.pop() == 15);
  73.     assert(s.pop() == 10);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement