链表类,如何访问嵌套节点结构的数据

Linked List class, how do I access the data of a nested node struct?

本文关键字:嵌套 节点 结构 数据 访问 何访问 链表      更新时间:2023-10-16

我正在尝试为我的作业编写这个链表类,并且我正在尝试在该类中编写一个"for_each"函数,该函数为用户提供对每个节点中的数据的只读访问权限。 但是,当我尝试访问节点中的数据时,出现错误,指出"EXC_BAD_ACCESS(code=1,地址=0x0)"如何在不泄漏内存的情况下访问我的数据? 我认为这就是错误所指的。

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <memory>
//template<typename T>
class LinkedList
{
private:
    struct Node
    {
        int data;
        std::shared_ptr<Node> next;
        Node(int d, std::shared_ptr<Node> n)
        :data(d)
        ,next(n)
        {}
        Node()
        {};
    };
    std::shared_ptr<Node> head;
    std::shared_ptr<Node> temp;
    std::shared_ptr<Node> current;
public:
    LinkedList()
       :head()
    {}
    LinkedList(LinkedList& other)
       :head(Clone(other.head))
    {}
    std::shared_ptr<Node> getStart()
    {
        return head;
    }
    void InsertAt(int value, std::shared_ptr<Node> &n)
    {
        n->next = std::make_shared<Node>(value, n->next);
    }
    void Insertion(int value)
    {
        Insertion(value, head);
    }
    void Insertion(int value, std::shared_ptr<Node> &n)
    {
        if (!n)
        {
            InsertAt(value, n);
            return;
        }
        if (value < n->data)
            Insertion(value, n->next);
        else
            InsertAt(value, n);
    }
    void Remove(int value)
    {
        Remove(value, head);
    }
    void Remove(int value, std::shared_ptr<Node>& n)
    {
        if (!n) return;
        if (n->data == value)
        {
            n = n->next;
            Remove(value, n);
        }
        else
        {
            Remove(value, n->next);
        }
    }
    void for_each(std::shared_ptr<Node> n)
    {
        if(!n) return;
        std::cout<<current->Node::data;  <---- //Here it keeps telling me I have bad_access
        for_each(current->next);               //"EXC_BAD_ACCESS(code=1, address=0x0)
    }
    std::shared_ptr<Node> Clone(std::shared_ptr<Node> n) const
    {
        if(!n) return nullptr;
        return std::make_shared<Node>(n->data, Clone(n->next));
    }
    LinkedList& operator = (const LinkedList& list)
    {
        this->Clone(list.head);
        return *this;
    }
};
#endif

不确定为什么在for_each合约中使用current,事实上,我认为没有理由current任何代码,有时,递归不是解决方案:

void for_each(std::shared_ptr<Node> n)
{
    if(!n) return;
    std::cout<<current->Node::data;  <---- this is never set to anything
    for_each(current->next);
}

试试这个:

void for_each(std::shared_ptr<Node> n)
{
    while(n)
    {
        std::cout << n->data << ' ';
        n = n->next;
    }
}