#include #include #include struct Node { int value { }; Node* next { }; }; class Circular_List { public: ~Circular_List() { while (tail != nullptr) { pop_front(); } } void push_front(int value) { Node* head { new Node { value } }; if (tail == nullptr) { head->next = head; tail = head; } else { head->next = tail->next; tail->next = head; } } int pop_front() { Node* head { tail->next }; int value { head->value }; if (head == tail) { tail = nullptr; } else { tail->next = head->next; } delete head; return value; } int front() const { return tail->next->value; } void rotate() { if (tail != nullptr) { tail = tail->next; } } void print(std::ostream& os) const { os << "[ "; if (tail != nullptr) { Node* head { tail->next }; do { os << head->value << " "; head = head->next; } while (head != tail->next); } os << "]"; } private: Node* tail { nullptr }; }; void test_const(Circular_List const& list) { assert( list.front() == 10 ); std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ 10 20 30 ]" ); } int main() { Circular_List list { }; { std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ ]" ); } list.rotate(); { std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ ]" ); } list.push_front(10); list.push_front(20); list.push_front(30); { std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ 30 20 10 ]" ); } // test rotate { list.rotate(); std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ 20 10 30 ]" ); } // test rotate together with pop_front() and push_front() { list.rotate(); list.pop_front(); list.rotate(); list.push_front(10); std::ostringstream oss { }; list.print(oss); assert( oss.str() == "[ 10 20 30 ]" ); } // test that print() and front() also works with const lists test_const(list); }