我的程序意外停止工作

时间:2016-10-18 14:19:18

标签: c data-structures

我尝试了codechef ide但是我遇到了运行时错误。

在Codeblocks上,程序会询问第一个输入,然后只是说程序已经停止正常工作。

如何确保我没有遇到任何运行时错误?

#include <stdio.h>
struct node
{
    int data;
    struct node* next;
};

struct node* head;

int main()
{
    head=NULL;
    int i,n,x;

    printf("\nEnter the number of nodes");
    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
        printf("\nEnter the value");
        scanf("%d",&x);
        Insert(x);
    }

    printf("\nHow many numbers?\n");
    Print();
    return 0;
}

void Insert(x)  /*To create new node in a linked list*/
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));

    temp->data=x;
    temp->next=NULL;

    struct node* temp1;
    temp1=head;

    while(temp1->next!=NULL)
    {
        temp1=temp1->next;
    }

    temp1->next=temp;
}

void Print()  /*to print the linked list*/
{
    struct node* temp;
    temp=head;
    printf("\nThe list is");

    while(temp!=NULL)
    {
        printf("\n%d",temp->data);
        temp=temp->next;
    }

    printf("\n");
}

1 个答案:

答案 0 :(得分:1)

列表的头部始终为NULL。 进行此更正并完成

 void Insert(x)
 {
        struct node* temp=(struct node*)malloc(sizeof(struct node));
        temp->data=x;
        temp->next=NULL;
        struct node* temp1;
        if(head==NULL)
        {
            head=temp;
        }
        else
        {
            temp1=head;
            while(temp1->next!=NULL)
            {
                temp1=temp1->next;
            }
            temp1->next=temp;
        }
 }