如何将节点添加到链表C++的前面?我想多了这个概念

How to add node to front of linked list C++? I'm overthinking the concept

本文关键字:前面 节点 添加 C++ 链表      更新时间:2023-10-16

我正试图在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);

就是这样。