【问题标题】:linked list creation - program stops working after taking the inputs链表创建 - 程序在输入后停止工作
【发布时间】:2014-10-12 11:31:14
【问题描述】:

在下面的链表创建程序中,输入后程序停止工作。 printf("\n nodes entered are:\n) 后面的代码没有运行。

for循环中的if用于创建头或开始节点。

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

【问题讨论】:

  • 使用符号编译(gcc 的选项-g)并使用调试器 (gbd) 运行代码,逐行逐行执行,您将获得启发。
  • 您可以通过拥有指向最后一个节点的指针来让自己更容易,然后在添加时只需修改 last 指向的内容。还创建一个读取 int 的函数,而不是在你的代码中撒上 scanf。例如int readInt() { char line[128]; fgets(line,sizeof(line),stdin); return atoi(line); }
  • @alk 可能。让我感到困惑的是,这个星球上有多少人在使用这堆热气腾腾的工具链,尤其是当 gcc 和 clang 完全免费且质量无限更高时。
  • @Codeluv 您尝试使用的技术称为 forward-chaining,一旦您掌握了单个 两级间接使用 C 中的指针。see example here.

标签: c linked-list


【解决方案1】:

更改此代码sn-p

    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,并且在执行此复合语句后将被删除。

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 2023-04-09
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多