Advertisement
bwukki

Untitled

May 24th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. class Node {
  7. public:
  8.     Node(int _data)
  9.     : data{_data}, prev{this}, next{this}
  10.     {}
  11.  
  12.     Node* getNext() const {
  13.         return next;
  14.     }
  15.  
  16.     Node* getPrev() const {
  17.         return prev;
  18.     }
  19.  
  20.     void setNext(Node* ptr) {
  21.         next = ptr;
  22.     }
  23.  
  24.     void setPrev(Node* ptr) {
  25.         prev = ptr;
  26.     }
  27.  
  28.     int getData() const {
  29.         return data;
  30.     }
  31.  
  32. private:
  33.     Node* prev;
  34.     int data;
  35.     Node* next;
  36. };
  37.  
  38. class DLinkedCircList {
  39. public:
  40.  
  41.     string toString() const {
  42.         string out{"["};
  43.         if (head != nullptr) {
  44.             int data{};
  45.             Node* currentNode{head};
  46.             do {
  47.                 data = currentNode->getData();
  48.                 out += to_string(data);
  49.                 if (currentNode->getNext() != head) {
  50.                     out += ", ";
  51.                 }
  52.                 currentNode = currentNode->getNext();
  53.             } while (currentNode != head);
  54.         }
  55.         out += "]";
  56.         return out;
  57.     }
  58.  
  59.     DLinkedCircList()
  60.     : head{nullptr}, size{0} {
  61.  
  62.     }
  63.  
  64.     ~DLinkedCircList() { //TODO NOT DONE
  65.         cout << "Destructor" << endl;
  66.         Node* nextObj{head->getNext()};
  67.         delete head;
  68.         head = nullptr;
  69.  
  70.  
  71.     }
  72.  
  73.     void push_back(int input) {
  74.         Node* newNode{new Node{input}};
  75.         //did the memory get allocated???
  76.         if (head == nullptr) {
  77.             head = newNode;
  78.         }
  79.         else { //add to end
  80.             Node* last{head->getPrev()};
  81.             last->setNext(newNode);
  82.             newNode->setPrev(last);
  83.             newNode->setNext(head);
  84.             head->setPrev(newNode);
  85.         }
  86.         size +=1;
  87.     }
  88.  
  89.     int getSize() {
  90.         return size;
  91.     }
  92.  
  93. private:
  94.     Node* head;
  95.     int size;
  96.  
  97. };
  98.  
  99. int main()
  100. {
  101.     DLinkedCircList testList{};
  102.     testList.push_back(99);
  103.     cout << testList.toString() << endl;
  104.     testList.push_back(105);
  105.     cout << testList.toString() << endl;
  106.     cout << "Hello world!" << endl;
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement