#include <stdio.h>
#include <stdlib.h>
typedef struct LINK
{
double data;
struct LINK *next;
}link;
link *init(link *head);
void print(link *head);
link *insert(link *head,double x);
void destroylink(link *head);
int main()
{
link *head=NULL;
double x;
head=init(head);
print(head);
printf("请输入插入数字: ");
scanf("%lf",&x);
head=insert(head,x);
print(head);
destroylink(head);
return 0;
}
link *init(link *head){
int i;
link *p,*pr;
for(i=0;i<10;i++){
p=(link *)malloc(sizeof(link));
if(p==NULL)exit(1);
p->data=i+1;
p->next=NULL;
if(head==NULL){
head=p;
pr=head;
}else{
pr->next=p;
pr=p;
}
}
return head;
}
void print(link *head){
link *p=head;
while(p!=NULL){
printf("%g ",p->data);//%g格式符出去实数多余的零
p=p->next;
}
printf("\n");
}
link *insert(link *head,double x){
link *p,*pr;
p=(link *)malloc(sizeof(link));
if(p==NULL)exit(1);
p->data=x;
p->next=NULL;
pr=head;
if(x < head->data){
p->next=head;
head=p;
}else{//注意循环结束条件,一般从p->next!=NULL和p!=NULL中选择
while(pr->next!=NULL && pr->next->data < x ){//pr所指向节点的后一个节点所存值大于x时,跳出循环
//注意第一个判断语句要在第二个前,因为一旦p->next==NULL,p->next->data这个东西是不存在的!
pr=pr->next;//pr不断指向下一个节点
}
p->next=pr->next;
pr->next=p;
}
return head;
}
void destroylink(link *head){
link *p=head;
while(p!=NULL){
head=p->next;
free(p);
p=head;
}
}
C