C++ 链表插入一个节点,前一个节点初始化

C++ Linked Lists Inserting a Node, Previous Node intialization

我正在看我的 C++ 教科书,其中有一个链表函数示例,用于在下面的列表中插入一个新节点....

Void NumberList::insertNode(double num)
{

ListNode *newNode;                   //A new node
ListNode *nodePtr;                   //To transverse the list
ListNode *previousNode = nullptr;    //The previous node

//Allocate a new node and store num there
newNode = new ListNode;
newNode->value = num;

//If there's no nodes in the list, make newNode the first node
if (!head)
{
    head = newNode;
    newNode->next = nullptr;
}
else      //Otherwise, insert newNode
{
   //Postion nodePtr at the head of the list
   nodePtr = head;
    
  //Initialize previousNode to nullptr.
  previousNode = nullptr;

 //Skip all nodes whose value is less than num. 
 while (nodePtr != nullptr && nodePtr->value < num)
 {
     previousNode = nodePtr;
     nodePtr = nodePtr->next;
 }

 //If the new node is the 1st in the list, insert it before all other nodes
 if (previousNode == nullptr)
 {
    head = newNode; 
    newNode->next = nodePtr;
 }
 else  //Otherwise insert after the previous node
 {
    previousNode->next = newNode;
    newNode->next = nodePtr;
  }
 }
}

`

我想知道为什么previousNode在代码中两次被初始化为nullptr?一次还不够好吗?

另一件事,谁能给我一个例子,说明如果存储的数据是字符或字符串,我们如何将节点插入到列表中?因为在这个例子的 while 循环中,它声明节点中的数据必须小于传递给函数的数据。

谢谢。

I was wondering why does previousNode get initialized to nullptr twice in the code?

没有理由。

Wouldn't once be good enough?

是的。

I was wondering why does previousNode get initialized to nullptr twice in the code? Wouldn't once be good enough?

一次就好了。第二个作业是多余的。

Another thing, could anyone give me an example of how we would insert a node into the list if the data being stored was a char or a string?

您将编写一个 Node 类型,其 value 成员可以存储您想要的类型(或使用 std::any, or template the whole thing on the stored type like std::list )。

Since in the while loop in this example, it states the data in the node has to be less than the data being passed to the function.

这不是它在做什么:

//Skip all nodes whose value is less than num. 
 while (nodePtr != nullptr && nodePtr->value < num) { ... }

通过根据值选择插入位置来保持列表排序。 “跳过所有节点”在这里的意思是“走过这些节点,以便新节点在列表中排在它们之后”[=1​​8=]