我似乎无法理解如何构建将节点添加到链表中的函数。
到目前为止,我有这个。
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/