创建指针的指针并在不修改原始指针的情况下对其进行修改

Creating a pointer of a pointer and modify it without modifying the original?

本文关键字:指针 修改 情况下 原始 创建      更新时间:2023-10-16

可以随意编辑标题,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)即可。