Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. // Will Sherwood C++ intro LinkedList implementation?
  2.  
  3. #include <iostream>
  4. #include <string>
  5. #include <math.h>
  6.  
  7. class Element {
  8. public:
  9. virtual ~Element() { }
  10.  
  11. virtual void print() = 0;
  12. };
  13.  
  14. class LinkedList : public Element {
  15. private:
  16. class Node : public Element {
  17. private:
  18. Element *element = 0;
  19. public:
  20. Node *next = 0;
  21.  
  22. Node(Node *next, Element *element) : next(next), element(element) { }
  23.  
  24. virtual ~Node() { delete element; }
  25.  
  26. virtual void print() { element->print(); }
  27.  
  28. void add(Node *node) { next = node; }
  29. };
  30.  
  31. Node *head;
  32. Node *tail;
  33. int size;
  34. public:
  35. LinkedList(Element *root) : head(new Node(0, root)), size(1), tail(head) { }
  36.  
  37. void addLast(Element *add) {
  38. Node *next = new Node(0, add);
  39. tail->add(next);
  40. tail = next;
  41. size++;
  42. }
  43.  
  44. void addFirst(Element *add) {
  45. Node *next = new Node(head, add);
  46. head = next;
  47. size++;
  48. }
  49.  
  50. void add(int position, Element *add) {
  51. if (position == 0) return addFirst(add);
  52. Node *find = head;
  53. while (--position) find = find->next;
  54. Node *next = find->next;
  55. find->add(new Node(next, add));
  56. }
  57.  
  58. int length() { return size; }
  59.  
  60. void remove(int position) {
  61. Node *find;
  62. if (!position) {
  63. find = head;
  64. head = find->next;
  65. delete find;
  66. return;
  67. }
  68. find = head;
  69. while (--position) find = find->next;
  70. Node *to_delete = find->next;
  71. find->add(to_delete->next);
  72. delete to_delete;
  73. size--;
  74. }
  75.  
  76. virtual void print() {
  77. Node *k = head;
  78. while (k) {
  79. k->print();
  80. k = k->next;
  81. }
  82. }
  83.  
  84. virtual ~LinkedList() {
  85. while (head) {
  86. Node *old = head;
  87. head = head->next;
  88. delete old;
  89. }
  90. }
  91. };
  92.  
  93.  
  94. class Int_Ele : public Element {
  95. private:
  96. int x;
  97. public:
  98. Int_Ele(int x) : x(x) { }
  99.  
  100. virtual void print() { std::cout << x << std::endl; }
  101. };
  102.  
  103. int main() {
  104. LinkedList list(new Int_Ele(15));
  105. list.addLast(new Int_Ele(30));
  106. list.addLast(new Int_Ele(45));
  107. list.addLast(new Int_Ele(60));
  108.  
  109. list.remove(3);
  110. list.addFirst(new Int_Ele(0));
  111. list.addFirst(new Int_Ele(-15));
  112.  
  113. list.remove(2);
  114.  
  115. list.add(4, new Int_Ele(101));
  116. list.print();
  117.  
  118. list.~LinkedList();
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement