如何替换链表中某个节点的数据

How to replace data in a certain node in a linked list?

本文关键字:节点 数据 链表 何替换 替换      更新时间:2023-10-16

我在课堂上有一个使用链表的练习。我对这门语言相当陌生,但我已经试过了。指令告诉我们"迭代直到找到NodeData,然后使用集合替换数据"。c++中的"集合"是什么?我在网上找过了,什么也找不到。我唯一能想到的就是把节点指向别的地方。例如:head->NULL。但是,如果我只是简单地替换数据,这真的有必要吗?为了替换数据,我尝试了temp->order = NEWDATA。这是正确的实现吗?这似乎并不奏效。可能是代码中其他部分的错误。

bool OrderLL::Modify(Order * NodeData) {
    OrderNode *temp = head;
    if (temp == NULL) {
        cout << "Empty List";
    }
    else {
        while (temp != NULL) {
            if (temp->order == NodeData) {
                //not sure if this is the proper way of deleting data inside a node
                delete anOrder;
               //HOW DO I REPLACE THE DATA IN THIS PART?
            }
            temp = temp->next;
        }
    }
return false;
}

顺便说一句,我真的不明白为什么我所有的问题都一直收到不满意的投票。是因为它们是基本的c++问题吗?它们对我来说不是很基本。我知道这个网站看不起"跑题/聊天讨论",但我只是不明白我的问题出了什么问题。

您在问题中提到了"replace",所以只是猜测,但可能您希望替换节点本身,而不仅仅是数据。在这种情况下,它会像这样

if(curr_node->data == to_replace_data){
  curr_node->next = new_node;
  new_node->next = curr_node->next->next;
  free( curr_node->next); //or return curr_node->next depending on what
                      // you are trying to do.
}