1

我正在尝试为我的作业编写这个 Linked List 类,并且我正在尝试在该类中编写一个“for_each”函数,该函数使用户可以只读访问每个节点中的数据。但是,当我尝试访问节点中的数据时,我收到一条错误消息:“EXC_BAD_ACCESS(code=1, address=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
4

1 回答 1

1

不知道你为什么current在你的for_each合同中使用,事实上,我认为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;
    }
}
于 2013-10-19T01:28:42.867 回答