peterdcasey

Untitled

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