Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Node {
- public:
- Node(int _data)
- : prev{this}, data{_data}, next{this}
- { }
- Node* getNext() const {
- return next;
- }
- Node* getPrev() const {
- return prev;
- }
- void setNext(Node* ptr) {
- next = ptr;
- }
- void setPrev(Node* ptr) {
- prev = ptr;
- }
- int getData() const {
- return data;
- }
- private:
- Node* prev;
- int data;
- Node* next;
- };
- class DLinkedCircList {
- public:
- DLinkedCircList()
- : head{nullptr}, size{0} {
- }
- ~DLinkedCircList() {
- cout << "destructor" << endl;
- }
- string toString() const {
- string out{"["};
- if (head != nullptr) {
- int data{};
- Node* ptr{head};
- do {
- data = ptr->getData();
- out += to_string(data);
- if (ptr->getNext() != head) {
- out += ", ";
- }
- ptr = ptr->getNext();
- } while (ptr != head);
- }
- out += "]";
- return out;
- }
- void push_back(int val) {
- Node* newNode{new Node{val}};
- // did the memory get allocated???
- if (head == nullptr) {
- head = newNode;
- }
- else { // add to end
- Node* last{head->getPrev()};
- last->setNext(newNode);
- newNode->setPrev(last);
- newNode->setNext(head);
- (*head).setPrev(newNode);
- }
- size += 1;
- }
- private:
- Node* head;
- int size;
- };
- int main()
- {
- {
- DLinkedCircList dlc{};
- dlc.push_back(99);
- dlc.push_back(49);
- dlc.push_back(29);
- cout << dlc.toString() << endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment