c++ - 如何在单链表的开头插入
问题描述
我试图在列表的开头插入节点,但无法插入,我认为插入的逻辑似乎是正确的
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,
解决方案
您需要通过引用插入传递指针:
void Insert(Node* &t, int pos, int x)
推荐阅读
- android - Android相机捕获会话错误的纵横比
- php - 如何在 PHP 中等待信号量或锁定文件时实现超时?
- r - 将数据帧从 R Studio Cloud 传输到 GoogleSheets 似乎非常慢
- c# - 处理在同一端点上侦听的多个 UDP 套接字
- typescript - 无法使用多个文件部署 Google Cloud Functions
- python-3.x - 如果它们是另一个网络的子网,如何从列表中删除网络地址
- regex - 尽管在正则表达式测试器中匹配,为什么 bash 中的这个正则表达式与该行不匹配?
- r - 如何在 R 中重新排序 geom_point ggplot2 图?
- c# - C#string.Equals如何设置默认的StringComparison?
- python - Matplot 直方图导致很多行