I'm looking for a help to understand linked list. I have such a task: aclass DNAList:
First of all, I try to do push_back(DNA* newDNA) method. Any help, please?
Thank you.
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;
}
The simplest way of having a linked list of DNA*
, would be to use the standard <list>
container and use list<DNA*>
. And to avoid memory leaks, even 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()
:
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()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.