【发布时间】: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