Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include "node.h"
  3. using namespace std;
  4.  
  5. template <class U>
  6. class SLL {
  7.  
  8. Node<U> * headPtr;
  9. int size;
  10.  
  11. public:
  12. // default constructor
  13. SLL(){
  14. headPtr = nullptr;
  15. size = 0;
  16. }
  17.  
  18. // destructor
  19. ~SLL(){
  20. Node<U> *next;
  21. while(headPtr != nullptr)
  22. {
  23. next = headPtr->next;
  24. delete headPtr;
  25. headPtr = next;
  26. }
  27. }
  28.  
  29. Node<U>* getHeadPtr(){
  30. return headPtr;
  31. }
  32.  
  33. // insert (item1, item2) to the list
  34. void insert(U item1, U item2){
  35. Node<U> *n = new Node<U>();
  36. n->SSN = item1;
  37. n->name = item2;
  38. n->next = nullptr;
  39.  
  40. if(headPtr == nullptr)
  41. headPtr = n;
  42. else
  43. {
  44. Node<U> last = headPtr;
  45. while(last->next != nullptr)
  46. last = last->next;
  47. last->next = n;
  48. }
  49. size++;
  50. }
  51.  
  52. // if find the item1 value, return the pointer to the node
  53. // otherwise, return nullptr
  54. Node<U>* search(U item1){
  55. Node<U> *curr = headPtr;
  56. while(curr != nullptr)
  57. {
  58. if(curr->item1 == SSN)
  59. return curr;
  60. curr = curr->next;
  61. }
  62.  
  63. return nullptr;//not found
  64. }
  65.  
  66. // remove the node with key value: item1
  67. bool remove(U item1){
  68. Node<U> *prev = nullptr, *curr = headPtr;
  69.  
  70. while(curr != nullptr)
  71. {
  72. if(curr->SSN == item1)
  73. break;
  74. prev = curr;
  75. curr = curr->next;
  76. }
  77.  
  78. if(curr == nullptr) //not found
  79. return false;
  80.  
  81. if(curr == headPtr) //remove head node?
  82. headPtr = curr->next;
  83. else
  84. prev->next = curr->next;
  85.  
  86. delete curr;
  87. size--;
  88. return true;
  89. }
  90.  
  91. int getSize(){
  92.  
  93. return size;
  94. }
  95.  
  96. // display the SSN values of each node in the linked list
  97. void display(){
  98. Node<U>* temp;
  99. temp = headPtr;
  100. while (temp!= nullptr) {
  101. cout << temp->SSN << endl;
  102. temp = temp->next;
  103. }
  104. }
  105. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement