c++ - 在C++中设置节点的内存地址

标签 c++ list nodes

我似乎无法理解如何构建将节点添加到链表中的函数。

到目前为止,我有这个。

void StringList::add(string value){
StringNode *temp = new StringNode;
temp->data = value;
temp->next = NULL;

if(head==NULL){
    head = temp;
    temp = NULL;
}

我不明白每次添加到列表时如何设置前一个节点的内存地址。理想情况下,我会给自己一个尾节点,但是我得到了一个驱动程序和一个头文件,它们将保持不变。任何见解将不胜感激。

最佳答案

如果你想在没有维护tail的情况下将新节点添加到列表的末尾,则每次都必须遍历整个列表:

void StringList::add(string value){
  StringNode *temp = new StringNode;
  temp->data = value;
  temp->next = NULL;

  if(head==NULL){
     head = temp;
  }
  else {
     StringNode* last = head;
     while (last->next) {
       last=last->next;
     }
     last->next = temp;
  }
}

关于c++ - 在C++中设置节点的内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295453/

相关文章:

java - AVL Tree节点旋转导致节点消失

c++ - 默认模板参数的模板推导

c++ - 这种情况的双向数据结构

c++ - Boost.Spirit.Qi : dynamically create "difference" parser at parse time

python - 将多个列表映射到字典

python - 在类里面创建列表的更好方法?

python - 如何比较元组(int)的元素以确定它是否存在于列表中

c++ - 如何以线程安全的方式从多个文本文件中删除某些字符?

c - 我的程序替换链表中所有节点中的所有字符串数据类型

javascript - 节点等待不等待 promise