C++基于shared_ptr实现的单链表无法正确追加节点问题求助
问题原因
你代码里的核心问题出在链表追加节点的遍历逻辑上:
- 你当前写的
while (ptr != nullptr)循环执行结束后,ptr已经是脱离链表的空指针,它是构造函数内的局部shared_ptr变量,你给它赋值temp的操作完全不会修改链表上任何节点的next成员,所以新节点根本没有挂到链表上。 - 正确的逻辑应该是遍历到当前节点的
next成员为空时就停止,此时ptr指向链表的最后一个有效节点,只需要把新节点赋值给ptr->next就能完成追加。
修复后的代码
#include <vector> #include <memory> struct Node { Node(int x, Node *next = nullptr) : x{x}, next{next} {} int x; std::shared_ptr<Node> next; }; class LinkedList { public: LinkedList(std::vector<int> const &v) { // 额外修正:用size_t匹配vector的size返回值,避免类型不匹配警告 for (std::size_t i = 0; i < v.size(); ++i) { auto temp = std::make_shared<Node>(v[i], nullptr); if (head == nullptr) { head = temp; } else { auto ptr = head; // 修正遍历终止条件,找到最后一个有效节点就停止 while (ptr->next != nullptr) { ptr = ptr->next; } ptr->next = temp; } } } std::shared_ptr<Node> head = nullptr; }; int main() { auto v = std::vector<int>{1, 2, 3}; auto l = LinkedList{v}; }
内容的提问来源于stack exchange,提问作者CD86
相关产品推荐
相关产品推荐

