在下面的代码中:插入功能不能插入超过2个节点。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node * next;
};
struct node * insertl(struct node * head,int value)
{
if(head==NULL)
{
struct node * temp= malloc(sizeof(struct node));
temp->val = value;
temp->next=NULL;
head=temp; printf("%d",value);
return head;
}
if(head->next==NULL)
{
struct node * temp= malloc(sizeof(struct node));
temp->val = value;
temp->next=NULL;
head->next = temp; printf("%d",value);
return head;
}
struct node *head1=head;
while(!head1->next)
{
head1=head1->next;
printf("%d",head1->val);
}
struct node * temp= malloc(sizeof(struct node));
temp->val = value;
temp->next=NULL;
printf("%d",temp->val-90);
head1->next = temp;
return head;
}
void print(struct node *head)
{ printf("\n");
struct node * temp = head;
while(temp!=NULL)
{
printf("%d\t",temp->val);
temp=temp->next;
}
}
int main()
{ struct node * h =NULL;
h=insertl(h,1);
h=insertl(h,4);
h=insertl(h,1);
h=insertl(h,4);
print(h);
}
我之间使用了printf语句来检查代码出错的地方。 显示输出:1,4。为什么代码不正确?
答案 0 :(得分:2)
struct node *head1=head;
while(!head1->next)
^
我认为你正试图追加&#34;结束&#34;列表中你的意思是while(head1->next)
。