【问题标题】:linked list not printing output链表不打印输出
【发布时间】: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-&gt;next = new Node; // linking to new node 是不正确的。您已经有一个新的 Node,您之前分配了它并且其值是正确的,称为 newNode。这就是您应该分配给temp-&gt;next 的内容。

标签: c++ class linked-list


【解决方案1】:

你的显示功能没问题。

问题是你在addNode() 中有 2 个逻辑缺陷:

  • 您没有在列表中正确存储字符串。在为 botName 赋值之前,您正在将 botName 赋值给 newNode-&gt;name_。所以你所有的节点都有空字符串。

  • 如果列表不为空,则您正确地迭代到列表的末尾,但随后您分配了一个新的空白节点,而不是分配您之前填充的 newNode

试试这个:

void linkedBotList::addNode(){
    std::string botName;    
    std::cin >> botName; // <-- move up here
    
    Node* newNode = new Node();
    newNode->name_ = botName;
    newNode->next = nullptr;

    if(head == nullptr){
        head = newNode;
    }
    else {
        Node* temp = head;
        while(temp->next != nullptr){
            temp = temp->next;
        }
        temp->next = newNode; // <-- linking to new node
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    相关资源
    最近更新 更多