C++链表节点存储机器人的重命名功能实现求助
机器人链表重命名功能修复及逻辑解释
我正在进行一个学校项目,开发一款Robot Guider来追踪机器人的移动、距离、速度等数据。其中需要实现机器人重命名功能,但机器人对象存储在链表的Node节点中。我查阅了一些资料但对网上的示例感到困惑,尝试编写了rename函数但运行异常,现附上RobotList和Robot两个类的代码,希望有人能帮忙解决并解释实现逻辑:
RobotList.hpp 代码
#ifndef RobotList_hpp #define RobotList_hpp #include "Robot.hpp" #include <stdio.h> #include <iostream> class RobotList{ private: class Node{ public: Robot* val; Node* next = nullptr; Node(std::string aName) { val = new Robot; val->setName(aName); } }; Node* head = nullptr; Node* tail = nullptr; public: RobotList() = default; ~RobotList(); void display() const; bool isEmpty(); Robot* find_nth(); void updateList(); void addNode(std::string name); void deleteNode(std::string name); void rename(); void robotDist() const; }; #endif /* RobotList_hpp */
Robot.hpp 代码
#ifndef Robot_hpp #define Robot_hpp #include <stdio.h> #include <iostream> #include <algorithm> class Robot{ private: int x, y, curSpeed, totDist; std::string name; char lastCommand; bool stop_; int off_or_on; public: std::string getName() { return name; } void setName(std::string a) { this->name = a; } int getTotDist() { return totDist; } void moveRobot(); int findRobot(); }; #endif /* Robot_hpp */
我编写的异常rename函数
void RobotList::rename(){ std::string new_name; std::cout << "Which robot do you want to rename?"<< std::endl; std::cin >> new_name; Node* temp = head; while(!head){ if(temp->val->getName() == new_name){ // update list with user input new_name // reassign a node that holds a string value } } temp = temp->next; // rest of list til nullptr }
错误分析与修复
原代码的核心错误
- 变量命名混淆:输入的是要修改的机器人旧名字,却命名为
new_name,逻辑混乱 - 循环条件错误:
while(!head)表示仅当链表为空时才循环,完全不符合遍历链表的需求 - 遍历逻辑错误:循环体内部没有移动
temp指针,会陷入死循环;temp = temp->next放在循环外,只会执行一次,毫无意义 - 缺少重命名操作:找到目标机器人后,没有接收用户输入的新名字,也没有调用
setName完成修改
修正后的rename函数
void RobotList::rename(){ // 1. 获取要重命名的机器人旧名字 std::string old_name; std::cout << "Which robot do you want to rename?" << std::endl; std::cin >> old_name; // 2. 从链表头部开始遍历 Node* temp = head; bool found = false; while(temp != nullptr){ // 3. 匹配到目标机器人 if(temp->val->getName() == old_name){ std::string new_name; std::cout << "Enter new name for the robot: " << std::endl; std::cin >> new_name; // 4. 调用Robot类的setName方法完成重命名 temp->val->setName(new_name); std::cout << "Robot renamed successfully!" << std::endl; found = true; break; // 找到目标后直接退出循环,无需继续遍历 } temp = temp->next; // 移动到下一个节点 } // 5. 处理未找到目标机器人的情况 if(!found){ std::cout << "Robot with name '" << old_name << "' not found!" << std::endl; } }
逻辑解释
- 输入旧名字:先让用户输入需要修改的机器人原名称,明确操作目标
- 遍历链表:用
temp指针从链表头节点head开始,逐个访问每个节点,直到temp为nullptr(遍历完整个链表) - 匹配目标:对比每个节点中Robot对象的名字,找到匹配项后,提示用户输入新名称
- 执行重命名:调用Robot类提供的
setName方法,直接修改机器人的名字(因为Node中存储的是Robot指针,修改指针指向对象的属性会直接生效) - 反馈结果:无论是否找到目标机器人,都给用户明确的操作反馈,提升交互体验
内容的提问来源于stack exchange,提问作者Noah M
相关产品推荐
相关产品推荐

