List.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #pragma once
  2. #include <iostream>
  3. using namespace std;
  4. class LineListException : public exception {
  5. public:
  6. const char* what() const noexcept override {
  7. return "LineList Exception";
  8. }
  9. };
  10. template <class T> class LineListElem {
  11. T data;
  12. LineListElem* next;
  13. public:
  14. LineListElem(const T& adata, LineListElem* anext);
  15. const T& getData() const;
  16. LineListElem* getNext();
  17. template <class U> friend class LineList;
  18. };
  19. template <class T> class LineList {
  20. LineListElem<T>* start;
  21. public:
  22. LineList();
  23. ~LineList();
  24. LineListElem<T>* getStart();
  25. void deleteFirst();
  26. void deleteAfter(LineListElem<T>* ptr);
  27. void insertFirst(const T& data);
  28. void insertAfter(LineListElem<T>* ptr, const T& data);
  29. template <class U> friend ostream& operator <<(ostream& out, LineList<U>& list);
  30. };
  31. template <class T> LineListElem<T>::LineListElem(const T& adata, LineListElem<T>* anext) {
  32. data = adata;
  33. next = anext;
  34. }
  35. template <class T> LineListElem<T>* LineList<T>::getStart() {
  36. return start;
  37. }
  38. template <class T>
  39. LineListElem<T>* LineListElem<T>::getNext() {
  40. return next;
  41. }
  42. template <class T> const T& LineListElem<T>::getData() const {
  43. return data;
  44. }
  45. template <class T> LineList<T>::LineList() {
  46. start = 0;
  47. }
  48. template <class T> LineList<T>::~LineList() {
  49. while (start)
  50. deleteFirst();
  51. }
  52. template <class T> void LineList<T>::insertFirst(const T& data) {
  53. LineListElem<T>* second = start;
  54. start = new LineListElem<T>(data, second);
  55. }
  56. template <class T> void LineList<T>::deleteAfter(LineListElem<T>* ptr) {
  57. if (ptr && ptr->next) {
  58. LineListElem<T>* temp = ptr->next;
  59. ptr->next = ptr->next->next;
  60. delete temp;
  61. }
  62. }
  63. template <class T> void LineList<T>::deleteFirst() {
  64. if (start) {
  65. LineListElem<T>* temp = start->next;
  66. delete start;
  67. start = temp;
  68. }
  69. else throw LineListException();
  70. }
  71. template <class T> void LineList<T>::insertAfter(LineListElem<T>* ptr, const T& data) {
  72. if (ptr) {
  73. LineListElem<T>* temp = ptr->next;
  74. ptr->next = new LineListElem<T>(data, temp);
  75. }
  76. }
  77. template <class T> ostream& operator <<(ostream& out, LineList<T>& list) {
  78. LineListElem<T>* ptr = list.start;
  79. if (!ptr)
  80. out << "EMPTY ";
  81. else
  82. while (ptr) {
  83. out << ptr->getData() << ' ';
  84. ptr = ptr->getNext();
  85. }
  86. return out;
  87. }