【发布时间】: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