Advertisement
nokkvikarls

Untitled

Feb 21st, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. //
  2. // linkedlist.h
  3. // Forritunarverkefni 5
  4. //
  5. // Created by Nokkvi Karlsson on 2/21/18.
  6. // Copyright © 2018 Nokkvi Karlsson. All rights reserved.
  7. //
  8.  
  9. #include "queue.h"
  10. #include "stack.h"
  11. #include "node.h"
  12.  
  13. #ifndef linkedlist_h
  14. #define linkedlist_h
  15.  
  16. class EmptyException { };
  17.  
  18. template <class T>
  19. class LinkedList : public Stack<T>, public Queue<T>
  20. {
  21.  
  22. public:
  23. LinkedList(){
  24. head = NULL;
  25. tail = NULL;
  26. }
  27.  
  28. virtual ~LinkedList(){
  29. Node<T> *tmp = head;
  30. while(head != NULL) {
  31. head = head->next;
  32. delete tmp;
  33. tmp = head;
  34. }
  35. head = NULL;
  36. tail = NULL;
  37. }
  38.  
  39. void headInsert(T data){
  40. head = new Node<T>(data, head);
  41. if(tail == NULL) {
  42. tail = head;
  43. }
  44. }
  45.  
  46. void tailInsert(T data) {
  47. if(head == NULL) {
  48. headInsert(data);
  49. }
  50. else {
  51. Node<T> *node = new Node<T>(data, NULL);
  52. tail->next = node;
  53. tail = node;
  54. }
  55. }
  56.  
  57. T headRemove() {
  58. if(head == NULL) {
  59. throw EmptyException();
  60. }
  61. T data = head->data;
  62. Node<T> *tmpNode = head;
  63. head = head->next;
  64. if(head == NULL) {
  65. tail = head;
  66. }
  67. delete tmpNode;
  68. return data;
  69. }
  70.  
  71. void push(T data) {
  72. headInsert(data);
  73. }
  74.  
  75. T pop() {
  76. return headRemove();
  77. }
  78.  
  79. void add(T data) {
  80. tailInsert(data);
  81. }
  82.  
  83. T remove() {
  84. return headRemove();
  85. }
  86.  
  87. void print(ostream& outs) const {
  88. Node<T>* currNode = head;
  89. while(currNode != NULL) {
  90. outs << currNode->data << " ";
  91. currNode = currNode->next;
  92. }
  93. }
  94.  
  95. private:
  96. Node<T>* head;
  97. Node<T>* tail;
  98. int itemCount;
  99.  
  100. };
  101.  
  102.  
  103. #endif /* linkedlist_h */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement