首页 文章

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

提问于
浏览
0

我正在寻求帮助来理解链表 . 我有这样一个任务:aclass DNAList:

  • 此类是一个链接的节点列表,其中包含指向(不是副本)DNA对象的节点,并且至少应包含:

  • 适当的构造函数和析构函数

  • 要存储的数据成员:指向列表的头指针

  • DNANode结构或类,它包含指向DNA对象的指针和指向DNANode对象的"next"指针(如果您使用的是双向链接列表,则为"prev"指针) .

  • 一种push_back(DNA * newDNA)方法,它将一个节点添加到列表的末尾

  • 一个find(int id)方法,如果列表中存在带有id的DNA对象,则返回DNA *;否则返回NULL

  • 删除具有登录号id的DNA条目并删除相应节点的obliterate(int id)方法

  • 一个int size()方法,它返回列表中的元素数

首先,我尝试做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 回答

  • 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() .

相关问题