简体   繁体   中英

How should I format a namespace with all different linked lists?

I want make a very simple namespace 'list' kind of like 'std' with libraries like 'singly' and 'doubly'. How can I modular the code so that I can only use variables I need to (circular vs non-circular)?

I imagine that I can just add a 'struct node* prev' to the struct that the list is using, but if the user decides to not do circular, it would always be 'nullptr' causing in an unnecessary variable. The second way I imagine is with having 2 different classes...

namespace list{
    struct snode{
        int data;
        struct snode* next;
    };

    class singly{
        public:
            singly();
            singly(unsigned long long amount=0, bool circular=0, bool userCreated=0, bool empty=0);
            ~singly();

            void create(unsigned long long amount=0, bool circular=0, bool userCreated=0, bool empty=0);
            void display();
            void destroy();
        private:
            snode* HEAD;
            unsigned long long amount;

            bool empty;
            bool circular;
            snode* TAIL;
    };
}

I expect with this namespace to do the following..

include "singly.h"

using namespace list;

singly list;

list.create(5);

list.display();

list.destroy();

or by not using the namespace something else...

list::singly list(7, 1, 0, 1);

list.display();

list.~list();

While this isn't an assignment or anything, I want this to be my go-to when I need to create a linked list ever in my life. Eventually, I want to create a namespace 'tree' and have further expansion with that. I almost want this to be as easy to use as the 'string' abstract data type.

short answer

It's impossible

long answer

I lied(ish). Create a base strict containing data, then create snode that inherits the data, implementing the pointer of base class. When going through the list check whether it fails.

struct A {
    int data;
    // make it polymorphic for the conversion
    virtual void function() {return;}
};

struct B : A {
    struct A* next;
};

int main()
{
    struct A end;
    struct B beginning;
    beginning.next = &end;
    struct B* buffer = &beginning;
    while(true) {
        buffer = dynamic_cast<struct B*>(buffer->next);
        if (buffer == nullptr) break;
    }
}

why it's pretty irrelevant

You only save at most (0 bytes) of memory per list. You save it using struct A, but struct A effectively has a function ptr/address aswell, which takes up space. This, however may be fixed by the compiler. And it takes longer to write worse code and the overall efficiency will be worse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM