0

随意编辑标题,engrish 有时会混淆而不是帮助。

我必须制作(不,我不能改变,这就是它必须的方式)简单的链表。不,我不能使用 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;

因为这只会用开始覆盖光标,使我的尝试无效。我仍然必须创建一个指针才能开始并能够调用 STRUCT 函数“-> next”

我怎样才能做到这一点 ?

* 还 *我怎样才能记住以前的节点?我可以这样做吗:

Node *previous;
previous = new Node;
previous = &(*begin); // ?
4

1 回答 1

1

听起来您想遍历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).

于 2012-04-02T17:33:16.217 回答