为节点分配指针地址

Assigning a pointer address to a node

下面是我在链表中​​插入一个数字的代码,如果head中包含的数字是多少。 错误出现在代码的最后一行 where

head -> next = &temp;

错误是:

无法在赋值中将 Node** 转换为 Node*。

我想做的是将 temp 的地址提供给 head.next,这样 head 就会指向 temp。

void LinkedList::insertAfter(int toInsert, int afterWhat)
{
       if(head->data == afterWhat)
       {

        Node* temp = new Node;
        temp->next = head->next;
        temp->data = toInsert;
        head->next = &temp;
       }
}

你需要

head->next = temp;

temp 的类型是 Node*,所以 &temp 的类型是 Node**,所以编译器正确地报错。

因为temp已经是一个指针,所以你不必写&temp。 使用 head->next=temp;