Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. template <typename T>
  7. class List {
  8. struct Node {
  9. T data;
  10. Node* next;
  11. };
  12. Node* root;
  13. int sz;
  14. public:
  15. List();
  16. T at(int);
  17. void set(int, T);
  18. void insert(int, T);
  19. void erase(int);
  20. int size();
  21. bool isEmpty();
  22. void print();
  23. };
  24.  
  25. template <typename T>
  26. List<T>::List() {
  27. root = NULL;
  28. sz = 0;
  29. }
  30.  
  31. template <typename T>
  32. T List<T>::at(int x) {
  33. if (x > size()) {
  34. exit(2);
  35. }
  36. Node* node = root;
  37. for (int i = 0; i < x; i++) {
  38. node = node->next;
  39. }
  40. cout << node->data << endl;
  41. }
  42. template <typename T>
  43. void List<T>::set(int x, T value) {
  44. if (x > size()) {
  45. exit(2);
  46. }
  47. Node* node = root;
  48. for (int i = 0; i < x; i++) {
  49. node = node->next;
  50. }
  51. node->data = value;
  52. }
  53.  
  54. template <typename T>
  55. int List<T>::size() {
  56. return sz;
  57. }
  58.  
  59. template <typename T>
  60. bool List<T>::isEmpty() {
  61. return size() > 0;
  62. }
  63.  
  64. template <typename T>
  65. void List<T>::insert(int x, T value) {
  66. if (root == NULL) {
  67. root = new Node;
  68. root->data = value;
  69. root->next = NULL;
  70. sz++;
  71. }
  72. else{
  73. Node* tmp = new Node;
  74. Node* current = new Node;
  75. Node* previous = new Node;
  76. current = root;
  77. if (x > size()) {
  78. printf("%d is out of bounds of the size %d", x, size());
  79. exit(2);
  80. }
  81. for (int i = 0; i < x; i++) {
  82. previous = current;
  83. current = current->next;
  84. }
  85. tmp->data = value;
  86. previous->next = tmp;
  87. tmp->next = current;
  88. sz++;
  89. }
  90.  
  91. }
  92.  
  93. template <typename T>
  94. void List<T>::erase(int x) {
  95. if (x > size()) {
  96. exit(2);
  97. }
  98. Node* current = new Node;
  99. Node* previous = new Node;
  100.  
  101. current = root;
  102. for (int i = 0; i < x; i++) {
  103. previous = current;
  104. current = current->next;
  105. }
  106. previous->next = current->next;
  107.  
  108. }
  109. template <typename T>
  110. void List<T>::print() {
  111. Node* node = root;
  112. int i = 0;
  113. while (node != NULL) {
  114. cout << node->data << " ";
  115. node = node->next;
  116. i++;
  117. }
  118. }
  119.  
  120. int main()
  121. {
  122. List<int> list;
  123. for (int i = 0; i <= 3; i++) {
  124. list.insert(i, i);
  125. }
  126. list.at(2);
  127. system("pause");
  128. return 0;
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement