【发布时间】:2022-11-18 14:56:54
【问题描述】:
我必须为学校项目动态分配机器人列表。在实际程序中,会有其他成员函数需要名称列表才能执行某些功能。
截至目前,我才刚刚了解到这个概念,并非常努力地尝试将我在网上看到的一些东西放在一起。目前的问题是我无法确定我的列表是否已正确存储——当我尝试调用我的列表显示功能时,我也得到了不稳定的输出。
如果可以的话请帮忙。此外,我很高兴听到任何关于任何事情的提示,因为我对编程还很陌生。
class Node{
public:
std::string name_;
Node* next;
};
class linkedBotList{
public:
linkedBotList() {head = nullptr;} //constructor
~linkedBotList(){}; // destructure
void addNode();
void display();
private:
Node* head;
};
int main(int argc, const char * argv[]) {
linkedBotList* list = new linkedBotList();
int siz;
std::cout << "How many Robots?" << std::endl;
std::cout << "What are the names?" << std::endl;
std::cin >> siz;
for(int i = 0; i < siz; i++){
list->addNode();
}
delete list;
return 0;
}
void linkedBotList::addNode(){
std::string botName;
Node* newNode = new Node();
newNode->name_ = botName;
newNode->next = nullptr;
std::cin >> botName;
if(head == nullptr){
head = newNode;
}
else {
Node* temp = head; // head is not null
while(temp->next != nullptr){ // go until at the end of the list
temp = temp->next;
}
temp->next = new Node; // linking to new node
}
}
void linkedBotList::display() {
if (head == NULL) {
std::cout << "List is empty!" << std::endl;
}
else {
Node* temp = head;
while (temp != NULL) {
std::cout << "Made it to display funct.\n";
std::cout << temp->name_ << " ";
temp = temp->next;
}
std::cout << std::endl;
}
}
我确实尝试了一些事情,比如切换我的 temp 变量,以及其他一些重新分配。也许有人可以快速发现问题并提供帮助?
【问题讨论】:
-
这个说法
temp->next = new Node; // linking to new node是不正确的。您已经有一个新的Node,您之前分配了它并且其值是正确的,称为newNode。这就是您应该分配给temp->next的内容。
标签: c++ class linked-list