gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:05:50 25 4
gpt4 key购买 nike

我正在寻找帮助来理解链表。我有这样一个任务:类 DNAList:

  1. 此类是一个节点链表,这些节点具有指向 DNA 对象(而非拷贝)的指针,并且至少应包含:
    • 适当的构造函数和析构函数
    • 要存储的数据成员: 指向列表的头指针
  2. 一个 DNANode 结构或类,它包含一个指向 DNA 对象的指针和一个指向 DNANode 对象的“下一个”指针(如果您使用的是双向链表,还有一个“上一个”指针)。
  3. 将节点添加到列表末尾的 push_back(DNA* newDNA) 方法
  4. 如果列表中存在具有 id 的 DNA 对象,则返回 DNA* 的 find(int id) 方法;否则返回 NULL
  5. 一种obliterate(int id)方法,删除具有登录号id的DNA条目并移除对应的节点
  6. 返回列表中元素数量的 int size() 方法

首先,我尝试执行 push_back(DNA* newDNA) 方法。有什么帮助吗?

谢谢。

DNA列表.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;
}

最佳答案

拥有 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() .

关于c++ - 将对象的指针添加到链表c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com