繁体   English   中英

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

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

在以下链接列表创建程序中,输入后,该程序停止工作。 printf("\\n nodes entered are:\\n)之后的代码未运行。

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;
}

更改此代码段

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

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

否则,在if语句的复合语句内,您将声明局部变量start,该变量将隐藏先前声明的变量start,并且将在执行此复合语句后将其删除。

暂无
暂无

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

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