我正在寻求帮助以了解链接列表。我有这样的任务: aclass DNAList:
首先,我尝试做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;
}
答案 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()
。