首页 > 解决方案 > 双向链表 remove()

问题描述

我最近试图复习 C++,所以一些语法错误可能就在我面前,但我似乎得到 ERROR: C2440 在下面尝试运行我的代码时。它在 main 的第一行中断并指向行:122

特别是这一行: Node* target_node = find_node_by_data(info);

错误 C2440 '正在初始化':无法从 void 转换为 Doublely_Linked_list::Node *'

感谢您过来帮助我解决这个问题。

template<typename AnyType>
void Doublely_Linked_list<AnyType>::find_node_by_data(AnyType const& information)const {
Node* current = head;

while (current) {
    if (current->information == information) {
        return current;
    }
    current = current->next;
}
return nullptr;
}


template<typename AnyType>
void Doublely_Linked_list<AnyType>::unlinkData(Doublely_Linked_list<AnyType>::Node* n) {
if (n->prev) {
    n->prev->next = n->next;
}
else {
    head = n->next;
    head->prev = nullptr;
}

if (n->next) {
    n->next->prev = n->prev;
}
else {
    tail = n->prev;
    tail->next = nullptr;
}
}


template<typename AnyType>
void Doublely_Linked_list<AnyType>::remove(AnyType info) {
Node* target_node = find_node_by_data(info);

if (target_node) {
    unlinkData(target_node);
    delete target_node;
}
}

int main() {
Doublely_Linked_list<double> list1;
double temp;
const double info = 2.1;
while (1)
{
    cin >> temp;
    if (temp == -1) break;
    else
    {
        list1.insertAtHead(temp);
    }
}
cout << list1;
list1.remove(info);
cout << list1;
}

在我用值填充节点的控制台中,我想填充节点值“2.1”并在完成填充 DLL 后将其删除。

标签: c++

解决方案


感谢您的帮助约翰,我在远离计算机一段时间后终于修复了它。我对该功能的解决方案是:

template<typename AnyType>
typename Doublely_Linked_list<AnyType>::Node* 
Doublely_Linked_list<AnyType>::find_node_by_data(AnyType const& information)const {
Node* current = head;

while (current) {
    if (current->data == information) {
        return current;
    }
    current = current->next;
}
return nullptr;
}

推荐阅读