链表类,如何访问嵌套节点结构的数据
Linked List class, how do I access the data of a nested node struct?
我正在尝试为我的作业编写这个链表类,并且我正在尝试在该类中编写一个"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;
}
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 嵌套的C 常数数据结构,没有初始化列表或明确命名所有节点-VC 2012过早破坏了内部元素
- 解析 AST 中的节点及其自己的(无限数量的嵌套)子节点
- 链表类,如何访问嵌套节点结构的数据
- 嵌套节点类操作符重载
- 解析第二个节点上嵌套的yml文件
- Boost属性树:移除嵌套节点