【问题标题】:How to make a function in C++ to delete a node from the linked list (node can be any except the first node) which matches the searched key如何在 C++ 中创建一个函数以从与搜索到的键匹配的链表中删除一个节点(节点可以是除第一个节点之外的任何节点)
【发布时间】:2021-04-18 18:55:17
【问题描述】:

我有一个名为DeleteData 的函数,我用它来从我的链表中删除任何节点。

void DeleteData(Node *node, int key)
{
   Node temp;
   //If key is in the first node itself
   if (node != NULL && node->read_data() == key)
   {
      temp = *node->next;
      node->next = NULL;
      delete node;
      cout << "New List";
      // It's just a function that reads all data from the linked list given the head reference.
      ListTraverse(&temp);
      return;
   }
   //If key is not in first node
else if (node->read_data() != key)
{
    while (node != NULL && node->read_data() != key)
    {
        // Function to loop thorugh all the nodes
    }
    if (node->read_data() == key)
    {
        //Steps to do, If node is found
    }
}
else
{
    cout<<"Invalid Search key";
}

}

这个DeleteData 被设计为接受两个参数,1。第一个节点的参考2。一把钥匙。我需要删除具有匹配键作为其值的节点。我已经成功制作了第一部分,即当密钥仅在第一个节点中时,但我无法设计它,以便如果在第一个节点中找不到密钥,它应该继续搜索其余节点。

Node 是具有此定义的 C++ 类

class Node
{
private:
  int data;

public:
  Node *next;
  void push_data(int x)
  {
      data = x;
  }
  int read_data()
  {
     return data;
  }
};

【问题讨论】:

  • Check out the Community addition to this answer。如果它不能彻底解决您的问题,请提出相关问题。
  • 不,我认为它没有解决我的问题
  • 这很奇怪。它完全符合您的要求。
  • 使用 ideone.com 分享您的完整代码
  • @JahirulIslamMonir 不推荐使用所有代码。请改用minimal reproducible example。此外,理解问题所需的所有信息都必须包含在问题中。链接腐烂,被防火墙阻止,通常很麻烦。如果需要更多代码才能正确回答问题,而且在这种情况下您可能是对的,那么如果代码不再可用,将来的人们将无法理解答案。

标签: c++ linked-list pass-by-reference singly-linked-list function-definition


【解决方案1】:

首先,应用单一职责原则:

分别搜索要删除的节点和删除它。

将工作与决定如何处理结果分开。

这样,任何错误都很难隐藏在混乱中,并且很容易修复。

Node*& findNode(Node*& root, int key) {
    auto p = &root;
    while (*p && (*p)->data != key)
        p = &(*p)->next;
    return *p;
}
void deleteNode(Node*& node) {
    if (node)
        delete std::exchange(node, node->next);
}
bool deleteNode(Node*& root, int key) {
    auto& node = findNode(root, key);
    if (!node) return false;
    deleteNode(node);
    return true;
}

【讨论】:

    【解决方案2】:

    对于初学者,指定头节点的参数应具有引用类型。

    函数可以通过以下方式声明和定义

    bool DeleteData( Node * &head, int key )
    {
        Node **current = &head;
    
        while ( *current && ( *current )->read_data() != key )
        {
            current = &( *current )->next; 
        }
    
        bool success = *current != nullptr;
    
        if ( success )
        {
            Node *tmp = *current;
            *current = ( *current )->next;
            delete tmp;
        }
    
        return success;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多