c++ - 我可以以这种方式为链表实现 push_back 方法吗?
问题描述
我已经为这样的链接列表做 push_back 方法:
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data,
Node* next = nullptr){
this->data = data;
this->next = next;
}
};
Node* head = nullptr;
void push_back(int data){
if(head == nullptr){
head = new Node(data);
}
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
但我想知道是否可以在另一个节点之后添加一个节点(我说的是这段代码,见下文):
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
不使用条件:
while(current->next != nullptr)
{current = current->next;}
,而是做:
while(current != nullptr){current = current->next;}
这样做时,我们将当前指针均衡为一个 nullptr。从那时起是否可以在末尾添加一个新节点并将该节点链接到整个列表?
还是while(current != nullptr)
不利于 push_back() 的概念?
解决方案
您可以通过将指针指向您希望更改的指针来执行类似的操作。
void push_back(int data){
Node** current = &head;
while(*current != nullptr) { current = &(*current)->next; }
*current = new Node(data);
}
作为奖励,您不再有空列表的特殊情况。
推荐阅读
- excel - Excel宏以特定间隔复制行
- jupyter-notebook - 在没有外部 IP 的情况下将 Jupyter Notebook 连接到服务器
- visual-studio - Azure Dev Ops:无法确定源代码管理服务器
- android - 如何使用 Firebase 联系具体的应用用户?
- javascript - 在下拉取消选择时更改对象数组中的值
- javascript - 如何使用 onSelect 查找选定对象的值?
- javascript - Google Maps API Location Express:您是否将脚本与初始化地图的代码一起嵌入到布局文件中?
- python - 基于带有循环的模式匹配两个列表的元素
- sql - 使用 VBA 将表从 sql server 导出到访问表
- javascript - jQuery 平滑滚动以在移动设备上使用固定菜单锚定