Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1.  
  2.  
  3. #include "stdafx.h"
  4. #include <iostream>
  5.  
  6. template<typename T>
  7. class list_node {
  8. private:
  9. T data;
  10. list_node* p_next;
  11.  
  12. public:
  13. list_node(const T& data) : data(data), p_next(nullptr) { }
  14. ~list_node() { }
  15.  
  16. void connectNew(list_node* p_to_new) {
  17. p_next = p_to_new;
  18. }
  19.  
  20. list_node<T>* getNext() {
  21. return p_next;
  22. }
  23.  
  24. void setData(const T& new_data) {
  25. data = new_data;
  26. }
  27.  
  28. T getData() const {
  29. return data;
  30. }
  31. };
  32.  
  33. template<typename T>
  34. class list {
  35. private:
  36. list_node<T>* head;
  37.  
  38. public:
  39. list() : head(nullptr) { }
  40.  
  41. ~list() {
  42. list_node<T>* next;
  43. while (head != nullptr) {
  44. list_node<T>* next = head->getNext();
  45. delete head;
  46. head = next;
  47. }
  48. }
  49.  
  50. void push_tail(const T& data) {
  51. list_node<T>* current = head;
  52. while (current->getNext() != nullptr)
  53. current = current->getNext();
  54.  
  55. list_node<T>* new_node = new list_node<T>(data);
  56. current->connectNew(new_node);
  57. }
  58.  
  59. T pop_tail() {
  60. list_node<T>* prev = head;
  61. while (prev->getNext()->getNext() != nullptr)
  62. prev = prev->getNext();
  63.  
  64. T data = prev->getNext()->getData();
  65. delete prev->getNext();
  66. prev->connectNew(nullptr);
  67.  
  68. return data;
  69. }
  70. };
  71.  
  72.  
  73. int main()
  74. {
  75. list<int> my_list;
  76. std::cout << my_list.pop_tail() << std::endl;
  77.  
  78. my_list.push_tail(1);
  79. my_list.push_tail(1);
  80. my_list.push_tail(1);
  81. my_list.push_tail(1);
  82. system("pause");
  83.  
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement