如何将节点添加到链表C++的前面?我想多了这个概念
How to add node to front of linked list C++? I'm overthinking the concept
我正试图在C++中的链表前面添加一个节点。我已经开发了添加到列表末尾的代码,这对我的大脑来说比后者更容易理解。这是我的代码:
该类
struct ListNode
{
double value;
ListNode *next;
ListNode(double value1, ListNode *next1 = NULL)
{
value = value1;
next = next1;
}
};
ListNode *head; // List head pointer
添加到列表末尾的函数
void LinkedList::add(double number)
{
if (head == NULL)
head = new ListNode(number);
else
{
// The list is not empty
// Use nodePtr to traverse the list
ListNode *nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
// nodePtr->next is NULL so nodePtr points to the last node
// Create a new node and put it after the last node
nodePtr->next = new ListNode(number);
}
}
我只是很难把所有的指针都转移到开头。
谢谢。
添加到开头很简单。不要把事情搞得更复杂。
ListNode * new_node = new ListNode(number);
if (head == nullptr)
{
head = new_node;
}
else
{
// Make the new node point to the (old) head.
new_node->next = head;
// Make the head pointer point to the new node.
head = new_node;
}
使用铅笔(或钢笔)和纸,在两种情况下绘制指针和节点。
情况1:空列表
插入前:
head-->nullptr
插入后:
+------+新节点-->|25|+-----+
+------+新节点-->|25|+-----+^|head---------------+
情况2:非空列表
插入前:
+------+头部-->|36|+-----+
插入后:
+------+新节点-->|25|+-----+
+------++-----+新节点-->|25|-->|36|+-----++------+^|头部------------------------+
+------++-----+新节点-->|25|-->|36|+-----++------+^|head---------------+
根据雷米的评论,上述内容可以简化为:
ListNode * new_node = new ListNode(number);
// Make the new node point to the (old) head.
new_node->next = head;
// Make the head pointer point to the new node.
head = new_node;
或者简单地说:
// Make the new node point to the (old) head, and
// make the head pointer point to the new node.
head = new ListNode(number, head);
添加到开头比在结尾更简单。
您需要将新节点的尾部设置为当前头,并将头设置为新节点。
head = new ListNode(number, head);
就是这样。
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 移除前面有空格的前2个字符串
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 如何在链表前面添加和返回节点
- 如何在提升property_tree前面添加节点
- 链表替换了前面的节点,而不是弹出到后面的节点上
- 在链表前面插入节点
- 如何将节点添加到链表C++的前面?我想多了这个概念
- 使用循环在链接列表的前面插入一个节点
- 将节点添加到链表的前面
- 正在链接列表前面添加节点