[英]Add pointer of object to linked list c++
I'm looking for a help to understand linked list. 我在寻找帮助来了解链表。 I have such a task: aclass DNAList:
我有这样一个任务:DNAList类:
First of all, I try to do push_back(DNA* newDNA) method. 首先,我尝试做push_back(DNA * newDNA)方法。 Any help, please?
有什么帮助吗?
Thank you. 谢谢。
DNAList.h DNA列表
#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 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;
}
The simplest way of having a linked list of DNA*
, would be to use the standard <list>
container and use list<DNA*>
. 具有
DNA*
链接列表的最简单方法是使用标准<list>
容器并使用list<DNA*>
。 And to avoid memory leaks, even list<shared_ptr<DNA>>
. 为了避免内存泄漏,甚至可以
list<shared_ptr<DNA>>
。
But your task seems to be an exercise to learn about linked lists. 但是您的任务似乎是学习链接列表的一种练习。 So here some tips for your own
push_back()
: 所以这里是您自己的
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
}
}
You can then inspire yourself from this to write your find()
and size()
(if you don't maintain the size in a data element), and even obliterate()
. 然后,您可以从中激发自己编写
find()
和size()
(如果您不保持数据元素的大小),甚至是obliterate()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.