创建指针的指针并在不修改原始指针的情况下对其进行修改
Creating a pointer of a pointer and modify it without modifying the original?
可以随意编辑标题,engrish有时会混淆而不是帮助。
我必须制作(,不,我不能更改,这是它必须的方式)简单的链表NO我不能使用STL或std::list。大部分都是在纸面上完成的,但我似乎在实现一个非常基本的游标时遇到了问题。
这是我在列表中的节点(部分):
struct Node {
int ap_nr;
Node *next;
};
我想浏览添加节点功能中的列表:
void add_node (Node **begin, int ap_nr)
{
stuff happens
}
这就是我如何调用函数:
add_node(&(*begin), ap_nr);
我想创建一个光标,它从开始(列表的开头)开始,使用cursor->next
遍历每个节点,直到到达结束(while (cursor->next!=0))
但我不能简单地说:
Node *cursor;
cursor = new Node;
cursor = begin;
因为这将简单地用begin覆盖光标,使我的尝试无效。我仍然需要制作一个指针来开始,并且能够调用STRUCT函数"->next"
我该怎么做?
*也*我如何记住上一个节点?我能做这个吗:
Node *previous;
previous = new Node;
previous = &(*begin); // ?
听起来您想要遍历add_node
函数中的列表。如果是,请尝试以下
void add_node (Node **ppBegin, int ap_nr)
{
if (!ppBegin) {
// Need to handle the case of bad user data here
}
// Traverse until we get the to the empty next value
while ((*ppBegin)->next) {
ppBegin = &((*ppBegin)->next);
}
// ppBegin now points to the address of where the new node should go
Node* created = new Node();
created->ap_nr = ap_nr;
*ppBegin = created;
}
注意:要开始调用此函数,只需使用add_node(&theListPointer)
即可。
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 使用指针算法修改函数中的 2D 数组
- 结构对象的指针成员在传递给函数时被修改
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- 如何在单个链表中交换两个节点的位置,只修改指针
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 当原始数据是常量时,修改指针指向的位置是 UB 吗?
- 将指向矢量的指针推回,然后修改其值会影响推送的值.我应该怎么做?
- 如果指针在C++为 NULL 则修改指针
- 修改跨 fork() 的指针中的数据
- 当我修改、更改和“删除”原始指针时,是否需要指针副本
- 通过指针修改子函数中函数的局部变量的内容
- 使用指针修改 C++ 初学者---字符串
- 通过这样的常量指针修改非常量指针是合法的
- 通过指向引用的指针修改类变量
- 使用指针修改内容
- 使用指针修改向量
- 通过构造过程中获得的指针修改const对象
- 用指针修改字节
- 通过常量指针修改使用 new 创建的对象是否合法