简体   繁体   English

链表创建-程序在输入后停止工作

[英]linked list creation - program stops working after taking the inputs

In the following linked list creation program, after input, the program stops working. 在以下链接列表创建程序中,输入后,该程序停止工作。 The code after printf("\\n nodes entered are:\\n) is not running. printf("\\n nodes entered are:\\n)之后的代码未运行。

The if in for loop is used for creation of head or start node. if in for循环用于创建头节点或起始节点。

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
    //creating a linked list
    typedef struct node
    {
    int data;
    struct node *link;
    }node;

int main()
{

    int i,n;
    node* temp;
    node* start=0;

    printf("Enter the no of elements in the linked list\n");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        if(i==0)                                                                //for first node
        {
        node* start=(node*)malloc(sizeof(node));
        scanf("%d",&(start->data));
        start->link=NULL;
        temp=start;
        }
        else
        {
            node *nextnode=(node *)malloc(sizeof(node));
            scanf("%d",&(nextnode->data));
            temp->link=nextnode;
            nextnode->link=NULL;
            temp=nextnode;                                                      //updating temp for next iteration
        }
    }
    printf("\n nodes entered are:\n");
    temp=start;
    while(temp->link!=NULL)
    {
            printf("%d ",temp->data);
            temp=temp->link;
    }

printf("%d",temp->data);
getch();
return 0;
}

Change this code snippet 更改此代码段

    if(i==0)                                                                //for first node
    {
    node* start=(node*)malloc(sizeof(node));

to

    if(i==0)                                                                //for first node
    {
         start=(node*)malloc(sizeof(node));

Otherwise inside the compound statement of the if statement you are declaring local variable start that hides previously declared variable start and that will be deleted after execution of this compound statement. 否则,在if语句的复合语句内,您将声明局部变量start,该变量将隐藏先前声明的变量start,并且将在执行此复合语句后将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM