如何在单向链表的开头插入

How to Insert at beginning of Singly Linked List

我试图在列表的开头插入节点,但无法插入,我认为插入的逻辑似乎是正确的

void display(Node *t)
{
    Node *p = t;
    while (p != 0)
    {
        cout << p->data << ",";
        p = p->next;
    }
}
void Insert(Node *t,int pos,int x)
{
    Node *temp=NULL;
    if(pos==0)
    {
       temp=new Node;
       temp->data=x;
       temp->next=t;
       t=temp;
    }
}
int main()
{
     Node *p = new Node;
     Node *q = new Node;

     p->data = 4;
     p->next = q;

     q->data=6;
     q->next=NULL;

     Insert(p,0,89);
     Insert(p,0,80);

     display(p);
}

我希望输出 80,89,4,6,

但我得到的实际输出是 4,6,

您需要通过引用传递指针到 Insert:

void Insert(Node* &t, int pos, int x)