在列表末尾插入具有第一个节点的数据的节点
Inserting a node at the end of the list with the data of the first node
我应该创建一个函数来显示第一个节点中的数据,然后使该节点成为列表中的最后一个节点。但我认为一个更简单的方法是,将第一个节点之后的节点作为列表的头,并在列表的末尾插入一个新节点,该节点包含前一个第一个节点的数据
代码附在下方
int places::showfirst()
{
node * current = head;
node * temp = current -> next;
node * temp2 = new node;
cout << "The first place you visited is nntn " << current -> place << endl;
current->place = temporary;
first = new char [strlen(temporary) +1];
strcpy(first,temporary);
while(current->next)
{
current = current -> next;
}
head = temp;
current -> next = temp2;
temp2 -> next = NULL;
temp2->place = first;
cout<<"THIS IS THE NEW LAST NODE " << temp2->place << endl;
return 1;
}
如有任何建议,我们将不胜感激,提前谢谢。
不需要内存重新分配或取消分配IMO。您只需更改链接并将现有的头节点转换为最后一个:
node * current = head;
node * temp = current -> next;
cout << "The first place you visited is nntn " << current -> place << endl;
while(current->next)
{
current = current -> next;
}
current -> next = head;
head -> next = NULL;
head = temp;
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 我正在尝试实现 BFS 并通过边缘计算所有访问的节点。但是我的代码给了我 0 计数,除了第一个
- pugiget 所有文本节点 (PCDATA),而不仅仅是第一个