Chain.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <iostream>
  2. #include "Node.h"
  3. class Chain
  4. {
  5. public:
  6. void* start;
  7. void* end;
  8. Chain()
  9. {
  10. start = nullptr;
  11. end = nullptr;
  12. }
  13. bool isNull() const
  14. {
  15. return start == nullptr;
  16. }
  17. template <typename T>
  18. void add(T value)
  19. {
  20. if(start==nullptr) {
  21. Node<T> tstart(value);
  22. start = &tstart;
  23. end = &tstart;
  24. return;
  25. }
  26. Node<T> node(value, static_cast<Node<T>*>(end));
  27. static_cast<Node<T>*>(end)->next = &node;
  28. end = &node;
  29. }
  30. template <typename T>
  31. Node<T> pop()
  32. {
  33. T value = static_cast<Node<T>*>(end)->value;
  34. if(static_cast<Node<T>*>(end)->prev == nullptr)
  35. {
  36. start = nullptr;
  37. end = nullptr;
  38. return value;
  39. }
  40. end = static_cast<Node<T>*>(end)->prev;
  41. static_cast<Node<T>*>(end)->next = nullptr;
  42. return value;
  43. }
  44. template <typename T>
  45. friend std::ostream &operator <<(std::ostream &os, Chain &c)
  46. {
  47. os << "( ";
  48. void* currentNode = c.start;
  49. while (static_cast<Node<T>*>(currentNode)->next!=nullptr)
  50. {
  51. os << *(static_cast<Node<T>*>(currentNode)) << " = ";
  52. currentNode = static_cast<Node<T>*>(currentNode)->next;
  53. }
  54. os << *(static_cast<Node<T>*>(currentNode)) << " )";
  55. return os;
  56. }
  57. };