Is a Linked-List implementation without using pointers possible or not?

前端 未结 14 1546
再見小時候
再見小時候 2020-12-01 07:57

My question is very simple, can one using C++, implement a link-list data structure without using pointers (next nodes)? To further qualify my question, I\'m mean can one cr

14条回答
  •  無奈伤痛
    2020-12-01 08:33

    One could create a list of cons-cells using temporaries, const references, and inheritance. But you'd have to be very careful not to keep any references to it beyond its lifetime. And you probably couldn't get away with anything mutable.

    This is based roughly on the Scala implementation of these lists (in particular the idea of using inheritance and a NilList subclass rather than using null pointers).

    template
    struct ConsList{
       virtual T const & car() const=0;
       virtual ConsList const & cdr() const=0;
    }
    
    template
    struct ConsCell:ConsList{
       ConsCell(T const & data_, ConsList const & next_):
            data(data_),next(next_){}
       virtual T const & car() const{return data;}
       virtual ConstList const & cdr() const{return next;}
    
       private:
         T data;
         ConsList const & next;
    }
    
    template
    struct NilList:ConsList{  
       // replace std::exception with some other kind of exception class
       virtual T const & car() const{throw std::exception;}
       virtual ConstList const & cdr() const{throw std::exception;}
    }
    
    void foo(ConsList const & l){
       if(l != NilList()){
          //...
          foo(NilList.cdr());
       }
    }
    
    foo(ConsList(1,ConsList(2,ConsList(3,NilList()))));
    // the whole list is destructed here, so you better not have
    // any references to it stored away when you reach this comment.
    

提交回复
热议问题