gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:40:38 25 4
gpt4 key购买 nike

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

到目前为止,我有这个。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com