将对象的指针添加到链表c ++

时间:2015-09-07 05:14:12

标签: c++ pointers linked-list

我正在寻求帮助以了解链接列表。我有这样的任务: aclass DNAList:

  1. 此类是具有指向(不是DNA副本)对象的节点的链接列表,并且至少应包含:
    • 适当的构造函数和析构函数
    • 要存储的数据成员:  指向列表的头指针
  2. 一个DNANode结构或类,它包含一个指向DNA对象的指针和一个" next"指向DNANode对象的指针(以及#34; prev"指针,如果您使用的是双向链接列表)。
  3. 将节点添加到列表末尾的push_back(DNA * newDNA)方法
  4. 如果列表中存在带有id的DNA对象,则返回DNA *的find(int id)方法;否则返回NULL
  5. 删除带有入藏号id的DNA条目并删除相应节点的删除(int id)方法
  6. 返回列表中元素数量的int size()方法
  7. 首先,我尝试做push_back(DNA * newDNA)方法。 有什么帮助吗?

    谢谢。

    DNAList.h

    #ifndef DNALIST_H
    #define DNALIST_H
    #include <iostream>
    #include <string>
    #include "DNA.h"
    
    
    class DNAList{
        //data members
        private:
            DNA* headPtr;
        public:
            DNAList();
            ~DNAList();
            struct DNANode;
            void push_back(DNA* newDNA);
            DNA* find(int id);
            void obliterate(int id);
            int size();
            DNA* getHeadPtr(){
                return headPtr;
            }
    
           void setHeadPtr(DNA* head){
                headPtr= head;
           }
    
    };
    
    #endif
    

    DNAList.cpp

    #include <iostream>
    #include <string>
    #include "DNAList.h"
    
    //constrictor
        DNAList::DNAList(){}
    //destructor
        DNAList::~DNAList(){
            delete headPtr;
            headPtr = NULL;
        }
    //struct that holds pointer to a DNA object  and a "next" pointer to a
    DNANode object
        struct DNANode{
            DNA* dnaPtr;
            DNANode* next;
        };
    //
        void push_back(DNA* newDNA){
    
            //dnaPtr = new DNANode;
    
        }
    
        DNA* find(int id){
    
        }
        void obliterate(int id){
    
        }
        int size(){
            return 0;
        }
    

1 个答案:

答案 0 :(得分:1)

拥有DNA*链接列表的最简单方法是使用标准<list>容器并使用list<DNA*>。并且为了避免内存泄漏,甚至是list<shared_ptr<DNA>>

但是你的任务似乎是学习链表的练习。所以这里有一些关于你自己push_back()的提示:

void push_back(DNA* newDNA)
{
    DNANode *element = new DNANode;// create a new node
    element->dnaPtr = newDNA;      // set it up  
    element->next = nullptr;       // it has no next element now

    if (headPtr==nullptr)          // hoping you have initalized the head at construction
         headPtr = element;        // either it's first element of empty list
    else {                         // or you need to find the last node
        DNANode *last = headPtr;   // starting at head
        while (last->next)         // and going from node to node
            last = last->next;  
        last->next = element;      // here you are
    }
}

然后,您可以从中激励自己编写find()size()(如果您不在数据元素中保持大小),甚至是obliterate()