在链表列表前插入节点
问题描述:
下面的代码应该在链表的前面添加一个节点并打印当前元素。但是运行这段代码会导致运行时错误并且程序终止。当询问有多少个数字时,我输入一个数字,然后显示“main.cpp已停止工作”。什么可能是错的?在链表列表前插入节点
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
Node* next;
};
struct Node* head;
using namespace std;
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
void Print()
{
Node* temp1=head;
while(temp1!=NULL)
{
printf("%d\n",temp1->data);
temp1=temp1->next;
}
printf("\n");
}
int main()
{
head=NULL;
printf("how many numbers?\n");
int n,i,x;
scanf("%d",n);
for(i=0;i<n;i++)
{
printf("Enter the number: \n");
scanf("%d",x);
Insert(x);
Print();
}
return 0;
}
答
它甚至不是一个链表问题:
int n,i,x;
scanf("%d",n);
应该
int n,i,x;
scanf("%d",&n);
(还有的是下面的另一个发生)
因为扫描整数他们需要他们的地址,而不是字符串。
+0
哦谢谢,最近研究指针,并将它们混合:(.. –
+0
顺便说一句,忘记我说你的链表(现在编辑出来),插入看起来不错。试图成为一个smartass需要更多的测试:) –
寻求调试帮助的问题('**为什么不是这个代码工作?**')必须包含所需的行为,特定的问题或错误以及在问题本身中重现**的最短代码** 。没有**明确问题陈述**的问题对其他读者没有用处。请参阅:[如何创建最小,完整和可验证示例](http://*.com/help/mcve)。 – Biffen
'scanf(“%d”,&n);'请注意&符号 –
在旁注:您应该学会清理 - 删除您在完成时分配的内存 – Unimportant