Sample Object-Oriented Singly-Linked ListΒΆ

// list_class.cpp

#include <iostream>
#include "cmpt_error.h"
#include <cassert>

using namespace std;

class List {
private:
        struct Node {
                int val;
                Node* next;
        }; // struct Node

        Node* head;
public:
        // Default constructor: creates a new empty list.
        List()
        : head(nullptr)
        { }

        // Destructor: called automatically when this list goes out of scope, or
        // is deleted. Thus no memory leaks are possible!
        ~List() {
                while (head != nullptr) {
                        Node* p = head;
                        head = head->next;
                        delete p;
                }
                cout << "List destructor: all list elements deleted\n";
        }

        bool is_empty() const {
                return head == nullptr;
        }

        int size() const {
                int count = 0;
                Node* p = head;
                while (p != nullptr) {
                        count++;
                        p = p->next;
                }
                return count;
        }

        void push(int x) {
                head = new Node{x, head};
        }

        int pop() {
                if (is_empty()) cmpt::error("can't pop empty list");
                Node* p = head;
                head = head->next;
                int result = p->val;
                delete p;
                return result;
        }

        void print() const {
                cout << "[";
                Node* p = head;
                while (p != nullptr) {
                        cout << p->val << " ";
                        p = p->next;
                }
                cout << "]";
        }

        void println() const {
                print();
                cout << "\n";
        }
}; // class List

void test1() {
        List lst;
        for(int i = 1; i <= 10; ++i) lst.push(i);

        lst.println();
}

void test2() {
        for(int i = 0; i < 10; ++i) {
                List lst;
                for(int j = 1; j <= i; ++j) {
                        lst.push(j);
                }
                assert(lst.size() == i);
                lst.println();
        }
}


int main() {
        // test1();
        test2();
}