这是一个简单的C程序,用于创建和显示单个链接列表.create()函数在上一个节点将节点数据作为参数后创建一个新节点.display()函数打印链接列表。该程序片段无法正常工作:
for(b=1;b<=5;b++) {
scanf("%d ",&a);
creat(a);
}
如果通过scanf()插入两个或三个值,则执行停止工作。 那有什么不对? 如果你跳过scanf()并输出如下所示的语句,它可以工作:
for(b=1;b<=5;b++) {
creat(7);
}
主要代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} *head=NULL;
typedef struct node Node;
void creat(int d);
void display();
int main()
{
int a,b;
printf("Input data to build a linked-list:\n");
for(b=1;b<=5;b++) {
scanf("%d ",&a); /*Error statement maybe*/
creat(a);
}
printf("The list is:-\n");
display();
return 0;
}
void creat(int d)
{
Node *new,*curr;
new=(Node *) malloc(sizeof(Node));
new->data=d;
new->next=NULL;
if(head==NULL)
{
head=new;
curr=new;
}
else
{
curr->next=new;
curr=new;
}
}
void display()
{
Node *p;
p=head;
while(p)
{
printf("%d--->",head->data);
p=p->next;
}
printf("NULL\n");
}
答案 0 :(得分:0)
在%d之后尝试没有空格 - scanf可能相当脆弱....
scanf("%d",&a);
答案 1 :(得分:0)
实际上问题是由函数creat()
-
else
部分正在创建问题。它应该是这样的 -
else
{
curr=head;
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=new;
}
遍历最后一个节点并添加新节点。
以及scanf
。
scanf("%d ",&a); /*Error statement maybe*/
^Remove the space.
同样在函数void display()
while(p)
{
printf("%d--->",head->data);
p=p->next;
}
您正在打印head->data
,但它没有递增到下一个,而p
设置为p->next
。因此,此功能不会打印整个链接列表。
printf
应该是这个 -
printf("%d--->",p->data);
答案 2 :(得分:0)
} *head=NULL;
更改为} *head=NULL, *curr;
scanf("%d ",&a);
更改为scanf("%d",&a);
Node *new,*curr;
更改为Node *new;
printf("%d--->", head->data);
更改为printf("%d--->", p->data);