在链表前面插入节点

Inserting node in front of Linked List

本文关键字:节点 插入 前面 链表      更新时间:2023-10-16

下面的代码应该在链表的前面添加一个节点并打印当前元素。但是运行此代码会给我运行时错误,程序终止。当询问有多少个数字时,我输入了一个数字,然后它显示"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("%dn",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);

(下面还有另一个出现)

因为扫描整数需要它们的地址,而不是字符串。