【发布时间】:2014-08-31 15:12:17
【问题描述】:
在下面的代码中:插入函数不能插入超过 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。为什么代码不正确?
【问题讨论】:
标签: c algorithm insert linked-list