首页 > 解决方案 > 如何在单链表的开头插入

问题描述

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

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,

标签: c++singly-linked-list

解决方案


您需要通过引用插入传递指针:

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

推荐阅读